2013-03-16 13 views
0

我有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來告訴我,我期待的準確值...

這種歸結爲兩個問題...

  1. 爲什麼我不能檢索f.object的值?
  2. 我想要做第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" %>)錯誤,實際上有更好的方法來做到這一點?

在此先感謝!

回答

0

原來我已把它放在了:selected在錯誤的位置...

原文:

<%= 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.select :attr_name_id, options_from_collection_for_select(AttrName.all,"id","description", f.object.attr_name_id), :prompt => "Select an attribute" %> 

修復該解決我的問題,屬性名現在出現如預期的先前保存的屬性。

它仍然不回答我原來的問題,爲什麼我無法獲得f.object的值打印出來,但至少原始原始問題已解決。

0

你需要使用PARAMS [:attr_name_id]到您的options_from_collection_for_select

<%= f.select :attr_name_id, options_from_collection_for_select(AttrName.all,"id","description", params[:attr_name_id].to_i), :prompt => "Select an attribute" %> 

希望它有助於

+0

我檢查了參數散列,並且attr_name_id也沒有出現在那裏。我*猜測*這是因爲我試圖將其作爲其「父」形式的一部分進行管理,而不是其自身。 – 2013-03-16 15:46:09

+0

這就是說,我非常感謝你,因爲它看着你的答案,這讓我意識到我已經在方法的錯誤部分放置了':selected'選項。 >< – 2013-03-16 15:49:08