2013-03-16 20 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