我有3个模型构成了has-many-through关联。fields_for构建器.object方法不允许我检索对象值
型号代码如下:
ItemAttrVal
模型(转换表)
class ItemAttrVal < ActiveRecord::Base
belongs_to :attr_name
belongs_to :registry_item
end
RegistryItem
模型
class RegistryItem < ActiveRecord::Base
has_many :item_attr_vals
has_many :attr_names, :through => :item_attr_vals
accepts_nested_attributes_for :item_attr_vals, :allow_destroy => :true
end
AttrName
模型
class AttrName < ActiveRecord::Base
has_many :item_attr_vals
has_many :registry_items, :through => :item_attr_vals
end
的RegistryItem
使用fields_for
如下:
<%= item.fields_for :item_attr_vals do |iav| %>
<%= render 'item_attr_val_fields', :f => iav %>
<% end %>
在局部,它看起来像这样:
<% logger.debug "object type is: #{f.object}"%>
<% logger.debug "some details are: #{f.object.attr_name_id}--"%>
<%= f.select :attr_name_id, options_from_collection_for_select(AttrName.all,"id","description"), :selected => f.object.attr_name_id, :prompt => "Select an attribute" %>
<%= f.text_field :raw_value %> <br />
1日2条调试线位,我的问题是有关的,但它首先涉及到第三行。 在那里,我试图提供一个“预先选定”值的下拉选择字段。这样当用户编辑RegistryItem时,将显示它们先前选择的AttrName。
我正在尝试使用f.object.attr_name_id
来设置该值,但它实际上并没有正确选择以前选择的值,而是仅转到第1个值。
一日2线调试然后我想确保我的f.object
方法有效?
当我在我的日志看,我看到以下内容:
object type is: #<ItemAttrVal:0x007fb3ba2bd980>
some details are: --
基本上,第一行显示我获得ItemAttrVal 第二行似乎没有检索到任何信息。
我也使用的调试检查,并在那里,我可以使用display f.object.attr_name_id
来告诉我,我期待的准确值...
这种归结为两个问题...
- 为什么我不能检索
f.object
的值? - 我想要做第3行(
<%= f.select :attr_name_id, options_from_collection_for_select(AttrName.all,"id","description"), :selected => f.object.attr_name_id, :prompt => "Select an attribute" %>
)错误,实际上有更好的方法来做到这一点?
在此先感谢!
我检查了参数散列,并且attr_name_id也没有出现在那里。我*猜测*这是因为我试图将其作为其“父”形式的一部分进行管理,而不是其自身。 – 2013-03-16 15:46:09
这就是说,我非常感谢你,因为它看着你的答案,这让我意识到我已经在方法的错误部分放置了':selected'选项。 >< – 2013-03-16 15:49:08