How to get relationship value in form_builder in rails

I have a table of products and categories. Category has_manyProduct and Product belongs_toCategory

When I work in the sandbox console, I can easily get the category the product belongs to:

@p = Product.find(29)
@p.category

However, on the product editing page, I cannot get the category to which it belongs.

<% 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'm trying to create an edit page for a product with a drop-down list containing all the categories, but I want the current category to be preselected.

Error:

undefined method `category' for #<ActionView::Helpers::FormBuilder:0xbb35f64>
+3
source share
1 answer

pcontains the form builder object, not the model instance. To access the model instance, follow these steps:

... ["#{p.object.category.id}"])%></td>

"".

: p form_for , #<Product>. #<ActionView::Helpers::FormBuilder:0xbb35f64>, . , . A FormBuilder object.

A FormBuilder , . <%= debug p %>, .

+11

Source: https://habr.com/ru/post/1732257/


All Articles