2010-06-26 24 views
0

我new.erb.html有这样的代码:Ruby on Rails的:如果定义submodel_attributes fields_for无能为力=

<% form_for(@ratification) do |f| %> 
    <%= f.error_messages %> 

    <% f.fields_for :user do |fhr| %> 
    <p> 
     <%= fhr.label :url %><br /> 
     <%= fhr.text_field_with_auto_complete :url %> 
    </p> 
    <% end %> 
<% end %> 

如果我有空Ratification.rb它是好的,fields_for工程确定。

但如果我写:

class Ratification < ActiveRecord::Base 
    belongs_to :user 
    accepts_nested_attributes_for :user 
end 

class Ratification < ActiveRecord::Base 
    belongs_to :user 
    def user_attributes=(attr) 
    ... 
    end 
end 

f.fields_for产量什么!为什么!?

的Rails:2.3.8

插件自动完成:repeated_auto_complete

+0

我编辑了我的答案... – 2010-06-26 16:18:33

回答

0

我相信你需要在你的控制器建立一个用户,像

# controller 
def new 
    @ratification = Ratification.new 
    @ratification.build_user 
end 

什么

<% f.fields_for :user, @ratification.user do |fhr| %> 
    # ... 
<% end %> 

我相信如果你使用

<% f.fields_for :user do |fhr| %> 

你应该有@user作为实例变量。但在你的情况下,你有@ratification.user

+0

不,这个解决方案不能帮助我... – petRUShka 2010-06-26 15:43:19

0

您不能重新定义user_attributes,因为您将覆盖ActiveRecord为其指定的标准行为。如果仍然知道这一点,您需要重新定义user_attributes尝试使用alias_method_chain

0

你不是这样做错了吗?如果批准属于用户,则用户模型应该接受批准的嵌套属性,而不是相反。

因此,如果用户有很多的批准,并且想要以单一形式提交多个用户的批准书,那么您将在用户模型中使用接受嵌套属性进行批准。

而且

@user = User.new 
2.times { @user.ratifications.build } # if you want to insert 2 at a time 

我试着做在控制台类似的东西,你会什么地方做的用户控制器:

@user = User.new 
@user.ratifications.build # this works 

但是,如果我做了

@ratification = Ratification.new 
@ratification.user.build # this fails 
0

我只是遇到同样的问题,并能够解决它。问题是,fields_for需要:user作为参数,而参数应该是@ratification.user

因此,与

<% f.fields_for @ratification.user do |fhr| %> 

这就是它取代

<% f.fields_for :user do |fhr| %> 

4

只是在f.fields_for

这样添加=EQUAL)后<%:

<%= f.fields_for :user do |fhr| %> 
    <p> 
     <%= fhr.label :url %><br /> 
     <%= fhr.text_field_with_auto_complete :url %> 
    </p> 
<% end %> 

OBS:你所要做的Rails中同样3

+0

谢谢!我完全错过了! – 2012-05-17 17:52:22