获取多态关联以通过验证

时间:2019-05-06 03:43:17

标签: ruby-on-rails activerecord

我有UserProfileBuyerSeller个对象。

class User
  has_many :profiles
end

class Profile
  belongs_to :user
  belongs_to :profileable, polymorphic: true
  validates :user, presence: true, uniqueness: { scope: :profileable_type }
end

class Buyer
  has_one :profile, as: :profileable, dependent: :destroy
  has_one :user, through: :profile # is this needed?
end

class Seller
  has_one :profile, as: :profileable, dependent: :destroy
  has_one :user, through: :profile # is this needed?
end

如果有效的配置文件不存在,我希望能够停止创建BuyerSeller

在rails控制台中,我当前可以通过创建一个没有Buyer值的Profile来创建user:。以下将创建一个不存在Buyer的{​​{1}}。

Profile

> Buyer.create(profile: Profile.create)

我想了解如何防止这种情况。我是否需要=> #<Buyer:0x00007fd44006cb80 id: 1, user_id: nil, created_at: Mon, 06 May 2019 03:41:04 UTC +00:00, updated_at: Mon, 06 May 2019 03:41:04 UTC +00:00> 或此类回调之一?

1 个答案:

答案 0 :(得分:1)

根据文章中提到的描述,您想以多态添加验证,因此只需在Model中添加状态验证即可,

class Buyer
  has_one :profile, as: :profileable, dependent: :destroy
  has_one :user, through: :profile # is this needed?

  validates :profileable, presence: true
  validates :user, presence: true
end

如果找不到用户,第二次验证将回滚事务。