Question

I have 2 models a User and Business. Many Users can Own a Business and a User can Own many Business.

A User could also be an Employee of a Business or a Client.

But just focusing on the Owner Business association I've been having trouble as I'm trying to use to a User id whilst referring to it as an Owner.

I've set up a BussinessesOwners join table and have the following models:

class User < ActiveRecord::Base
    has_many :businesses, through: :businesses_owners
end

class Business < ActiveRecord::Base
    has_many :owners,  :class_name => 'User', :foreign_key => "owner_id", through: :businesses_owners
end

class BusinessesOwners < ActiveRecord::Base
    belongs_to :users, :foreign_key => "owner_id"
    belongs_to :businesses
end

BusinessesOwners Migration:

class CreateBusinessOwners < ActiveRecord::Migration
  def change
    create_table :business_owners, :id => false do |t|
        t.integer :business_id
        t.integer :owner_id
    end
  end
end

How can I set up the association to refer to the User model as an Owner? - So Businesses.owners will return a list of users?

Was it helpful?

Solution

Personally, I like to name associations based on the associated tables, in other words: user_id instead of owner_id. And since you are not doing a HABTM relation, you're not bound to the "buisinesses_owners" convention and you can give the through-model a better name such as BusinessOwnership or even Ownership (e.g. if used polymorphically for any ownership relation between User and another model).

Please note that the belongs_to in the through-model must be singular. (Read the association out loud and you'll hear it doesn't make sense to use plural here.)

The following should thus work:

class User < ActiveRecord::Base
  has_many :businesses, through: :business_ownerships
  has_many :business_ownerships
end

class Business < ActiveRecord::Base
  has_many :owners,  through: :business_ownerships, source: :user
  has_many :business_ownerships
end

class BusinessOwnership < ActiveRecord::Base
  belongs_to :user
  belongs_to :business
end

And here are the migrations:

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :name
    end
  end
end

class CreateBusinesses < ActiveRecord::Migration
  def change
    create_table :businesses do |t|
      t.string :name
    end
  end
end

class CreateBusinessOwnerships < ActiveRecord::Migration
  def change
    create_table :business_ownerships do |t|
      t.references :user
      t.references :business
    end
  end
end

Please note: Unless you add extra attributes to BusinessOwnership or recycle it as a polymorphic Ownership model, it's not really necessary to do a "has_many through" here, you could just as well do to HABTM relations with join tables named according to the corresponding convention.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top