a person
a person

Reputation: 1706

Getting polymorphic association to pass validation

I have User, Profile, Buyer, and Seller objects.

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

I want to be able to stop creation of Buyer and Seller if a valid profile does not exist.

In the rails console, I am currently able to create a Buyer by creating a Profile without a user: value. The following will create a Buyer without a Profile existing.

> 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>

I would like to understand how to prevent this. Do I need one of the before_save or such callbacks?

Upvotes: 0

Views: 56

Answers (1)

Rohan
Rohan

Reputation: 2727

As per the description mentioned in the post, you want to add validation in polymorphic so just add the presence validation in the Model and it will work accordingly:

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

The second validation will rollback the transaction if user is not found.

Upvotes: 1

Related Questions