Getting fields_for and accepts_nested_attributes_for to work with a belongs_to relationship

前端 未结 4 759
暖寄归人
暖寄归人 2020-11-29 23:48

I cannot seem to get a nested form to generate in a rails view for a belongs_to relationship using the new accepts_nested_attributes_for facility o

相关标签:
4条回答
  • 2020-11-30 00:27

    I'm using Rails 2.3.5 and I noticed the same thing. Checking out the source for active_record's nested_attributes.rb, it looks like belongs_to should work fine. So it appears it might be a "nested forms" bug.

    I have a nested form exactly like yours, with User belongs_to :address, and Address is independent of the user.

    Then in the form, I just do <% f.fields_for :address_attributes do |address_form| %> instead of <% f.fields_for :address do |address_form| %>. Temporary hack until there's a better way, but this works. The method accepts_nested_attributes_for is expecting the params to include something like:

    {user=>{address_attributes=>{attr1=>'one',attr2=>'two'}, name=>'myname'}

    ...but fields_for is producing:

    {user=>{address=>{attr1=>'one',attr2=>'two'}, name=>'myname'}

    This way you don't have to add that has_one :account to your code, which doesn't work in my case.

    Update: Found a better answer:

    Here is the gist of the code I'm using to make this work right:

    Rails Nested Forms with belongs_to Gist

    Hope that helps.

    0 讨论(0)
  • 2020-11-30 00:33

    I'm a few months too late, but I was looking to solve this error and my situation was that I could not change the relationship to 'face the other way'.

    The answer really is quite simple, you have to do this in your new action:

    @account.build_owner
    

    The reason why the form did not display using fields_for was because it did not have a valid object. You had the right idea up there with:

    @account.owner.build
    

    However, this is not the way belongs_to work. This method is only generated with has_many and has_and_belongs_to_many.

    Reference: http://guides.rubyonrails.org/association_basics.html#belongs-to-association-reference

    0 讨论(0)
  • 2020-11-30 00:36
    class Account < ActiveRecord::Base
    
        belongs_to :owner  :class_name => 'User', :foreign_key => 'owner_id'
    end
    

    It works for me. :foreign_key => 'owner_id' was the key problem in my case.

    0 讨论(0)
  • 2020-11-30 00:42

    I think your accepts_nested_attributes is on the wrong side of the relationship. Maybe something like this would work?

    class Account < ActiveRecord::Base
      belongs_to :owner, :class_name => 'User', :foreign_key => 'owner_id'
      has_many :users
    end
    
    class User < ActiveRecord::Base
      belongs_to :account
      has_one :account, :foreign_key => :owner_id
      accepts_nested_attributes_for :account
    end
    

    For building the account you want to use build_account.

    You can see more examples in the docs.

    0 讨论(0)
提交回复
热议问题