Rails association in concerns

1.6k views Asked by At

I am using concerns for my rails application. I've different kind of users so I have made a loggable.rb concern.

In my concern I have

included do 
        has_one :auth_info 
    end

because every of my user that will include the concern will have an association with auth_info table.

The problem is, what foreign keys I need to put in my auth_info table?

E.G

I've 3 kind of users:

  1. customer
  2. seller
  3. visitor

If I had only customer, in my table scheme I would have put the field

id_customer

but in my case?

2

There are 2 answers

6
zwippie On

You can solve this with polymorphic associations (and drop the concern):

class AuthInfo < ActiveRecord::Base
  belongs_to :loggable, polymorphic: true
end

class Customer < ActiveRecord::Base
  has_one :auth_info, as: :loggable
end

class Seller < ActiveRecord::Base
  has_one :auth_info, as: :loggable
end

class Visitor < ActiveRecord::Base
  has_one :auth_info, as: :loggable
end

Now you can retrieve:

customer.auth_info # The related AuthInfo object
AuthInfo.first.loggable # Returns a Customer, Seller or Visitor

You can use rails g model AuthInfo loggable:references{polymorphic} to create the model, or you can create the migration for the two columns by hand. See the documentation for more details.

4
aashish On

Since user has roles 'customer', 'seller', 'visitor'. Add a column called role to Users table. Add a column called user_id to auth_infos table.

class AuthInfo < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_one :auth_info
end

you can do

 user = User.first
 user.auth_info 

Now you a additional logic to your concerns.