使用accepts_nested_attributes_for保存时,Rails会创建多余的子记录

时间:2014-11-19 22:57:53

标签: ruby-on-rails

在我的模特中:

class PaymentProfile < ActiveRecord::Base
  has_many :user_payment_profiles, inverse_of: :payment_profile
  accepts_nested_attributes_for :user_payment_profiles
end

class UserPaymentProfile < ActiveRecord::Base
  belongs_to :user
  belongs_to :payment_profile, inverse_of: :user_payment_profiles
end

class User < ActiveRecord::Base
  has_many :user_payment_profiles, dependent: :destroy
  has_many :payment_profiles, through: :user_payment_profiles, dependent: :destroy
end

在我的控制器中:

class PaymentProfilesController < ActionController::Base
  respond_to :json
  before_action :find_user

  def create
    @payment_profile = @user.payment_profiles.build(payment_profile_params)
    @payment_profile.creator_id = params[:user_id]
    @payment_profile.save
    respond_with @payment_profile
  end

  private

    def find_user
      @user = User.find(params[:user_id])
    end
end

我使用accepts_nested_attributes_for

通过json创建新的PaymentProfile和UserPaymentProfile记录
i.e POST /users/1/payment_profiles

{"payment_profile": {"amount":"200", "user_payment_profiles_attributes": [ {"user_id": "2"}, {"user_id": "3"} ]}}

所以PaymentProfilesController中的参数:创建动作

{"payment_profile"=>{"amount"=>"200", "user_payment_profiles_attributes"=>[{"user_id"=>"2"}, {"user_id"=>"3"}]}, "user_id"=>"1"}

但是Rails没有创建2个UserPaymentProfile实例,而是创建了3个!使用&#34; user_id&#34; =&gt;&#34; 1&#34; from params hash来自url / users / 1 / payment_profiles

如何解决问题?

1 个答案:

答案 0 :(得分:0)

我的错, 它应该是

@payment_profile = PaymentProfile.new(payment_profile_params)

而不是

@payment_profile = @user.payment_profiles.build(payment_profile_params)

rails正在自动创建连接模型