user4571629
user4571629

Reputation: 450

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

Upvotes: 2

Views: 1358

Answers (4)

Andrey Deineko
Andrey Deineko

Reputation: 52357

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.

Upvotes: 4

Rubysmith
Rubysmith

Reputation: 1175

You need to change your select tag according to this.

<%= 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 %></td>
    <td><%= f.select(:category_id, options_from_collection_for_select(Category.all, :category_id, :title)) %></td>            
</tr>           

Upvotes: 1

Richard Peck
Richard Peck

Reputation: 76774

collection_select is what you need:

<%= form_for @page do |f| %>
  <%= f.collection_select :category_id, Category.all, :id, :title %>          
  <%= f.submit %>
<% end %>

Upvotes: 0

Minato
Minato

Reputation: 4533

For Rails3(or may be less), if you've a Category model you can simply do.

f.select(:category, Category.select([:id,:title]).map { |c| [ c.id, c.title ] } , { include_blank: true })

Upvotes: 0

Related Questions