我有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