Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with xor conditions, rails, foreign keys and a sqlite database?

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

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:

  • Ruby 1.9.3
  • Rails 3.1.3
  • SQLite 3.7.3
like image 835
Robin Avatar asked Dec 28 '11 14:12

Robin


1 Answers

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
like image 126
mynameiscoffey Avatar answered Sep 30 '22 14:09

mynameiscoffey