Search code examples
ruby-on-railsruby-on-rails-4ruby-on-rails-5ruby-on-rails-6

Rails - form_for select that show my categories from db


I have Pages associated to my Categories
Now I have a form that I'm creating Pages

<%= form_for @page do |f| %>

<table>
    <tr>
        <td><%= f.label :title %></td>
        <td><%= f.text_field :title %></td>
    </tr>
    <tr>
        <td><%= f.label :desc %></td>
        <td><%= f.text_field :desc %></td>          
    </tr>
    <tr>
        <td><%= f.label :category_id %></td>
        <td><%= f.select(Page.all, :category_id, :title) %></td>            
    </tr>           
</table>    

<%= f.submit %> 


<% end %>

I'm trying to create a select dropdown that will show me all the categories that I have from my db, after I select one it will assign the Page that I'm creating to the Category that I'm choosing from the select dropdown


Solution

  • You should use

    f.select :category, Category.pluck(:title, :id)
    

    Be aware, that if your rails version is lower, that 4.x you can only use pluck with one column.