Rails - 在has_one belongs_to中同时创建父级和子级

时间:2014-09-09 13:08:46

标签: ruby-on-rails ruby belongs-to has-one

我是我做错了,但我看不到哪里。 我有这两个型号:

Subscription.rb(子)

class Subscription < ActiveRecord::Base
  attr_accessible :state, :subscriber_id, :subscriber_type, :last_payment

  belongs_to :subscriber, polymorphic: true

  validates :subscriber_id, presence: true
  validates :subscriber_type, presence: true
end

restorer.rb(父级)

class Restorer < User
  attr_accessible :firstname, :lastname, :restaurant_attributes, :subscription_attributes

  has_one :restaurant, dependent: :destroy, :autosave => true
  has_one :subscription, as: :subscriber, :autosave => true

  accepts_nested_attributes_for :restaurant
  accepts_nested_attributes_for :subscription

end

当我想要两个创建一个新的恢复器和一个新的订阅(同时) 它不起作用:

  def create
    @restorer = Restorer.create params[:restorer]
    @restaurant = @restorer.build_restaurant params[:restorer][:restaurant_attributes]
    @subscription = @restorer.build_subscription params[:restorer][:subscription_attributes]

    if @restorer.save
      ...
    else
      ...
    end
  end

1 个答案:

答案 0 :(得分:3)

查看评论和您的代码,看起来它不起作用的原因是因为Subscriber上的验证。 Restorer有一个SubscriptionSubscription属于Subscriber。您无处创建订阅者,因此订阅失败的原因是验证。您需要删除验证,或在Subscriber上设置经过验证的属性(subscriber_id和subscriber_type)。

你在创作中尝试做的事情有点粗糙,但如果你打算这样做的话应该看起来像这样:

def create
  @restorer = Restorer.create params[:restorer]

  # These two lines aren't needed if you are accepting nested attributes
  @restaurant = @restorer.build_restaurant params[:restorer][:restaurant_attributes]
  @subscription = @restorer.build_subscription params[:restorer][:subscription_attributes]

  subscriber = Subscriber.new params[:subscriber]
  @subscription.subscriber = subscriber

  if @restorer.save
    ...
  else
    ...
  end
end

顺便说一句,最好验证关系subscriber而不是ID subscriber_id

validates :subscriber, presence: true