Getting fields_for and accepts_nested_attributes_for to work with a belongs_to relationship

前端 未结 4 764
暖寄归人
暖寄归人 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: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.

提交回复
热议问题