【发布时间】:2013-03-16 14:17:28
【问题描述】:
我有 3 个模型组成了一个多通关联。
型号代码如下:
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 行调试行是我的问题所在,但它首先与第 3 行有关。 在那里,我试图为下拉选择字段提供“预选”值。这样当用户编辑 RegistryItem 时,他们之前选择的 AttrName 就会显示出来。
我正在尝试使用f.object.attr_name_id 来设置该值,但是它实际上并没有正确选择先前选择的值,而是直接转到第一个。
第一条两条调试线是我试图确保我的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" %>) 做错了,实际上有更好的方法吗?
提前致谢!
【问题讨论】: