What I want is, building this somehow with Rails 3.1:

If A has set an id for b_id, it shouldn't be possible to setting an id for c_id. And for sure vice versa too.
I wish I could do at the database level from a migration (check constraint?). Is this somehow possible? Or is it more affordable to do this in the model with validations?
My environment:
You can accomplish this through polymorphic associations, altho the schema won't look exactly like what you have, you can accomplish the same goal, having an item A belong to either a B or a C but never to both.
You can read more here: http://guides.rubyonrails.org/association_basics.html#polymorphic-associations
In the example given on that link, A is their Picture, and Employee and Proudct are your B and C:
(copied from source linked above):
class Picture < ActiveRecord::Base
belongs_to :imageable, :polymorphic => true
end
class Employee < ActiveRecord::Base
has_many :pictures, :as => :imageable
end
class Product < ActiveRecord::Base
has_many :pictures, :as => :imageable
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With