Can't update my nested model form for has_one association

前端 未结 3 1787
闹比i
闹比i 2020-12-08 15:09

I try to create a nested model form for the has_one association. (i\'m using Rails 4)

In my user, and adress model i have the following :

class User          


        
相关标签:
3条回答
  • 2020-12-08 15:32

    in your controller UsersController, in the update method, add the address: :id to the address permitted attributes. Like this:

    params.require(:user).permit(:user_name, address_attributes: [:id, :street]))
    
    0 讨论(0)
  • 2020-12-08 15:46

    There is an option to make it do a partial update if the record already exists:

    accepts_nested_attributes_for(:address, update_only: true)
    

    Documented here: http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html#method-i-accepts_nested_attributes_for

    0 讨论(0)
  • 2020-12-08 15:57

    This error usually indicates that there is an existing record for the has_one relationship. In other words, this particular user object already has an address record associated with it. This could happen while testing the form in the browser.

    In this case, it seems like Rails is trying to create a new address record, and it has to do with how your edit action is written.

    Try this:

    def edit
      @user = User.find(params[:id]) 
      @address = user.address || @user.build_address
    end 
    
    0 讨论(0)
提交回复
热议问题