Search code examples
ruby-on-railsrubydeviserelationshipbelongs-to

Rails belongs_to relationship with multiple possibilities


I'm trying to make a relationship where a model, Information, belongs_to either a User or a Client.

I thought about putting in my Information.rb

belongs_to :user
belongs_to :client

and in User.rb and Client.rb

has_one :information

But that makes it so that an information could belong_to both a User and a Client.

Is there a way to make it so that it can only belong to either or without just leaving one of the fields blank?

P.S. If it is needed I'm using Rails 4.2, Ruby 2.2.1, and Devise for my account authentication.

Thanks!


Solution

  • This sounds like an unusual association but it's a good fit for Polymorphic Association. In this case, you would declare a name for this association

    class Information < ActiveRecord::Base
      belongs_to :informational, polymorphic: true #or something like it
    
    class User < ActiveRecord::Base
      has_many informations, as :informational
    
    class Client < ActiveRecord::Base
      has_many informations, as :informational
    

    And you would also need to add two columns to Information informational_id, :integer and informational_type, :string

    and Client and User need a integer called informational_id that is indexed.