views:

57

answers:

3

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

A: 

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.

j.
No, this solution doesn't help me...
petRUShka
A: 

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.

Francisco
A: 

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
kentor