Reputation: 921
As an example, say I have a credit card that belongs to a user with an associated billing address.
One solution is that I assign the relationship in the create/update block. However, this really requires me to handle the errors such as blank id or non-existing record. Was hoping there was a better solution that i have overlooked.
I am interested in making sure that an address that belongs to another user is not assigned to the current user.
So, code for the create solution:
credit_card = current_user.credit_cards.create!(credit_card_params) do |credit_card|
credit_card.address = User.addresses.find(params['credit_card']['address_id'])
end
I haven't added the error handling yet and could push that to a class method in the User object and then call User.set_address('address_id') which also handles validation. Is there a better pattern for doing this?
Upvotes: 0
Views: 56
Reputation: 42799
If we look at it from the credit card point of view, you just want to make sure that the address_id
is unique, meaning the address_id
can't be used twice on two different credit cards.
class CreditCard < ActiveRecord::Base
validates :address_id, uniqueness: true
end
If a new credit card is initialized with an address_id
that belongs to another user the credit card becomes invalid.
Update: by adding a scope to the uniqueness validation, you allow duplication for a smaller set, which in your case would be the user_id
( if 2 creditcards have the same address, and the same user then that's fine )
class CreditCard < ActiveRecord::Base
validates :address_id, uniqueness: { scope: user_id }
end
Upvotes: 1