Relationship in Rails, how to declare in Active Record?

Asked

Viewed 665 times

0

I have a list of commercial establishments. Users, at first, are not registered in any of them. When he (the user) decides to register, a relationship is created between him and the establishment. It would be like the Facebook 'add friend' feature. But here’s the question:

What would be the relationship of the tables in the database? And in Active Record to be more specific? It would be a kind of dynamic relationship (if that exists)?

  • User can add more than one establishment?

  • Yes @Ricardo, you can.

1 answer

3


Let’s use the following nomenclature:

  • Shop: Business establishment
  • Customerlink: Association between business establishment and customer
  • Customer: Client

In the Active Record, your relationship would look like this:

class Shop < ActiveRecord::Base
  has_many :customerlinks
  has_many :customers, through: :customerlinks
end

class CustomerLink < ActiveRecord::Base
  belongs_to :shop
  belongs_to :customer
end

class Customer < ActiveRecord::Base
  has_many :customerlinks
  has_many :shops, through: :customerlinks
end

Browser other questions tagged

You are not signed in. Login or sign up in order to post.