Reputation: 429
I have a Product and Category table. Category has_many
Product and Product belongs_to
Category
When I work in console sandbox i can easily get the category a product belongs to by doing:
@p = Product.find(29)
@p.category
However, in the edit page of the Product I am not able to get the category it belongs to.
<% form_for :product, @products do |p| %>
<%= p.error_messages %>
<td><%=label "category", "Category"%></td>
<td><%=p.select :category_id, options_for_select(
@categories.map {|s| [s.name, s.id]},
["#{p.category.id}"])%></td>
So basically i am trying to have edit page for a product with a drop down that contains all categories but i want the current category preselected.
Error I get is:
undefined method `category' for #<ActionView::Helpers::FormBuilder:0xbb35f64>
Upvotes: 3
Views: 1390
Reputation: 5930
p
holds a form builder object, not your model instance. To access the model instance do this:
... ["#{p.object.category.id}"])%></td>
Note the "object".
Explanation: p
within the block scope of form_for
is not your product, so it is not of type #<Product>
. Instead it is a #<ActionView::Helpers::FormBuilder:0xbb35f64>
as the error message tells you. Thus it knows nothing about your model's properties. A FormBuilder
holds your form object in its object
method.
A FormBuilder holds other cool tools which may be useful. I suggest to do a <%= debug p %>
to find out more.
Upvotes: 11