开发者

Ruby on rails: fields_for do nothing if defined submodel_attributes=

I have such code in new.erb.html:

<% 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 %>  

If i have empty Ratification.rb it is ok, fields_for works ok.

But if I wrote:

class Ratification < ActiveRecord::Base
  belongs_to :user
  accepts_nested_attributes_for :user
end
开发者_开发问答

or

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

f.fields_for yields nothing! Why!?

Rails: 2.3.8

Plugin for autocomplete: repeated_auto_complete


just add an = (EQUAL) after <% in the f.fields_for

like this:

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

obs: you have to do the same in Rails 3


I believe you need to build a user in your controller, like

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

What about

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

?

I believe if you use

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

you should have @user as instance variable. But in your case you have @ratification.user.


You cannot redefine user_attributes since you will overwrite the standar behaviour that ActiveRecord specifies for it. If still knowing this you need to redefine user_attributes try using alias_method_chain.


Aren't you doing this wrong? If Ratification belongs to a user, then the user model should accept nested attributes for ratifications, not the other way around.

So if users have many ratifications, and if you want to submit multiple ratifications for a user in a single form, then you would use accept nested attributes for ratification in the user model.

And you would do somewhere in the users controller

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

I tried to do something similar in the console:

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

But if I did

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


I just encountered the same problem and was able to fix it. The problem was that fields_for takes :user as an argument while the argument should be @ratification.user

Hence, replace

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

with

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

That's it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜