简体   繁体   English

如何在rails中的form_builder中获取关系值

[英]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 类别has_many产品和产品belongs_to类别

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. p包含表单生成器对象,而不是模型实例。 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> . 说明: form_for的块范围内的p 不是您的产品,因此它不是 #<Product>类型。 Instead it is a #<ActionView::Helpers::FormBuilder:0xbb35f64> as the error message tells you. 相反,它是#<ActionView::Helpers::FormBuilder:0xbb35f64>因为错误消息告诉您。 Thus it knows nothing about your model's properties. 因此,它对您的模型的属性一无所知。 A FormBuilder holds your form object in its object method. FormBuilder将表单对象保存在其object方法中。

A FormBuilder holds other cool tools which may be useful. FormBuilder拥有其他可能有用的很酷的工具。 I suggest to do a <%= debug p %> to find out more. 我建议做一个<%= debug p %>来了解更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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