i have this form that saves the relation between 2 tables in my db
Treatments belongs_to :category
Category has_many :treatments
When a treatment is created it should save the id of the category and i want the category to be a drop down list, here is my code for the form :
<%= form_for(@treatment) do |f| %>
<div class="field">
<select>
<% Category.find(:all).each do |cat| %>
<option><%= cat.name %></option>
<% end %>
</select>
</div>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="actions">
<%= f.submit %>
</div>
Okey so i was able to display all the categories names but im kinda lost at how i should save the cat.id with the form
btw im quite new to rails if you haven’t noticed 🙂
any thoughts ?
UPDATE
here is the html that is generated
<div class="field">
<label for="treatment_category">Category</label>
<br>
<select id="category_category_id" name="category[category_id]">
<option value="">Velja flokk</option>
<option value="1">Nudd</option>
<option value="2">Heilun</option>
<option value="3">Nálastunga</option>
</select>
</div>
okey noticed an error in the html changed id="treatment_category_id" and now in my show view i see the categorie connected to the treatment but its name looks like Category:0x3eb7d90
here is my view, its just a basic scaffold but i added the .name
<p>
<b>Category:</b>
<%= @treatment.category.name %>
</p>
<p>
<b>Name:</b>
<%= @treatment.name %>
</p>
USE an HTML SELECT BOX and set the values to the id values and the text to the names of the categories.
If you need to save more than 1 id then you can use javascript to append a hidden input with the value of the id to save when the form is posted.