我可以在Rails中获取/访问form_builder.object的ATTRIBUTE吗?

时间:2017-05-31 06:07:21

标签: ruby-on-rails ruby activerecord rails-activerecord

我在这里提出了一个问题,因为这令我感到困惑:

我正在尝试使用以下模型创建嵌套属性表单:

class Recipe < ApplicationRecord
  has_many :ingredient_records, dependent: :destroy, inverse_of: :recipe    
  accepts_nested_attributes_for :ingredient_records, allow_destroy: true

class IngredientRecord < ApplicationRecord
  belongs_to :food, inverse_of: :ingredient_records
  belongs_to :recipe, inverse_of: :ingredient_records

我已经忽略了一些与之无关的模型部分。 (至少我希望如此)。

主要问题在于:当我在:编辑视图中执行此操作时:

<div class="nested-fields">
  <div class="field">
    <%= f.label :food_id %>
    <%= f.select :food_id, [[ f.object.food, f.object.food_id ]]%>

它输出一个带有&lt; #Food:x0203400291&gt;等选项的选择字段。 (form_builder对象,使用byebug验证它是带有断点的正确对象)

但是当我这样做时(它是 .name 部分):

<%= f.select :food_id, [[ f.object.food.name, f.object.food_id ]]%>

Rails会引发一个错误屏幕:undefined method ´name' for nil:NilClass(name是Food.model上的一个属性)。

你们觉得怎么样?我实际上是在尝试在rails视图中不允许的内容吗? (因为在select构建器之前放置一个byebug子句并且调用f.object.food.name返回值就好了)会很奇怪。提前谢谢!

0 个答案:

没有答案