3

I have created a categories model with a migration with a category_id (basically everything Mackenzie Child does in his video https://www.youtube.com/watch?v=814gCeOpM4o from 25minutes) and I want it to show up in my form.

It doesn't work, my collection_select wont show up on screen but it will show up in the source code, and when I 'remove' the css- framework materialize.

My code:

<div class="container"> 
<div class="row">
    <%= form_for @post do |f| %>
        <%= f.collection_select :category_id, Category.all, :id, :name, { prompt: "Choose a category" } %>
        <br>
        <%= f.label :title %>
        <%= f.text_field :title %>
        <br>
        <br>
        <div class="row">
            <div class="input-field col s12">
                <%= f.label :text %>
                <%= f.text_area :text, class: "materialize-textarea" %>
            </div>
        </div>

        <br>
        <br>
        <%= f.label :creator %>
        <%= f.text_field :creator %><br>
        <%= f.submit %>
    <% end %>   
</div>

How it's displayed in the source code:

    <select name="post[category_id]" id="post_category_id"><option value="">Choose a category</option>
        <option value="1">Marketing</option>
        <option value="2">Technology</option>
        <option value="3">Programming</option>
        <option value="4">Health and Fitness</option>
   </select> 
Jonny C
  • 1,943
  • 3
  • 20
  • 36
Ludvig Sørensen
  • 397
  • 4
  • 13

3 Answers3

4

I looked in the materialize documentation and i found out that i just had to add the class browser-default to my collection-select (link to docs http://materializecss.com/forms.html)

    <%= f.collection_select :category_id, Category.all, :id, :name, { prompt: "Choose a category" }, class: "browser-default" %> 
Ludvig Sørensen
  • 397
  • 4
  • 13
1

If you want your select boxes to render the Materialize CSS way instead of the browser default, then remove the browser-default class and initialize the select box with this code in the relevant .coffee file:

$(document).ready ->
  $('select').material_select
  return

look under app/assets/javascripts/ for the file to put it in.

Also if you are also using turbolinks with jQuery you will need to add the jquery.turbolinks gem to make the $document.ready function work.

Remember to restart your rails server after adding jquery.turbolinks

Toby 1 Kenobi
  • 4,717
  • 2
  • 29
  • 43
0

Based on Toby 1 Kenobi's answer and this one my solution, using Rails 5, was to change $(document).ready to $(document).on('turbolinks:load') like so:

$(document).on('turbolinks:load', function() {
  $('select').material_select();
}) 
Community
  • 1
  • 1
IanBussieres
  • 959
  • 13
  • 27