Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
829 views
in Technique[技术] by (71.8m points)

ruby on rails - Can't update my nested model form for has_one association

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 < ActiveRecord::Base
 has_one :address
 accepts_nested_attributes_for :address
end

class Address < ActiveRecord::Base
 belongs_to :user

end

my user controller :

class UsersController < ApplicationController
    .
    .
    .
    def edit
      @user = User.find(params[:id]) 
      @user.build_address if @user.address.nil?
    end 

    def update
      @user = User.find(params[:id])
      if @user.update(params.require(:user).permit(:user_name, address_attributes: [:street]))
        flash[:success] = "Profile updated successfully"
        sign_in @user
        redirect_to @user
      else
         flash.now[:error] = "Cannot updating your profile"
         render 'edit'
      end
    end
end

finally in my view i have :

= form_for(@user) do |f|
  = render 'shared/error_messages', object: f.object
  %div
    = f.label :user_name, "User name"
    = f.text_field :user_name
    = f.fields_for :address do |add|
      = addd.label :street
      = d.text_field :street
    = f.submit "Update"

When i try to fill street filed for the first time it works, but when i try to update i get the error : Failed to remove the existing associated address. The record failed to save after its foreign key was set to nil

any idea where is the error ? thank's

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...