Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 我可以获取/访问form#builder.object';Rails中的属性是什么?_Ruby On Rails_Ruby_Activerecord_Rails Activerecord - Fatal编程技术网

Ruby on rails 我可以获取/访问form#builder.object';Rails中的属性是什么?

Ruby on rails 我可以获取/访问form#builder.object';Rails中的属性是什么?,ruby-on-rails,ruby,activerecord,rails-activerecord,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 IngredientRec

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

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

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 ]]%>

它输出一个带有如下选项的select字段(form_builder对象,用byebug验证它是具有断点的正确对象)

但是当我这样做时(它是名称部分):


Rails会引发一个错误屏幕:nil:NilClass的
未定义方法“name”(name是Food.model上的一个属性)


你们觉得怎么样?我是否真的尝试了rails视图中不允许的内容?(将byebug子句放在select构建器之前,调用
f.object.food.name
返回的值很好,这会很奇怪)。提前谢谢

f.object.food和.name
可以解决99%的问题(或者
f.object.food.try(:name)
如果你使用的是Ruby<2.3)。这是一个很好的解决方法,谢谢。仍然让我困惑的是,为什么这样调用属性会引起错误。
<%= f.select :food_id, [[ f.object.food.name, f.object.food_id ]]%>