简体   繁体   中英

how to get a relationship value in form_builder in rails

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM