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.