Rails has_many虽然关联 - 指定键名

时间:2014-03-30 10:38:09

标签: ruby-on-rails model has-many-through

我有2个模型UserBusiness。许多用户可以拥有一个企业,用户可以拥有许多企业。

用户也可以是企业或客户的员工。

但是只关注业主商业协会,我一直遇到麻烦,因为我试图将其用作用户ID,同时将其称为所有者。

我已经建立了一个BussinessesOwners联接表并拥有以下模型:

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

如何设置关联以将用户模型称为所有者? - 那么Businesses.owners将返回一个用户列表?

1 个答案:

答案 0 :(得分:3)

就个人而言,我喜欢根据相关表格命名关联,换句话说:user_id而不是owner_id。既然你没有做HABTM关系,你就不会受到&#34; buisinesses_owners&#34;约定,您可以为直通模型提供更好的名称,例如BusinessOwnership甚至Ownership(例如,如果多态用于用户与其他模型之间的所有权关系)。

请注意,直通模型中的belongs_to必须是单数。 (大声读出协会,你会听到在这里使用复数词是没有意义的。)

以下应该有效:

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

以下是迁移:

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

请注意:除非您向BusinessOwnership添加额外属性或将其作为多态Ownership模型进行回收,否则不需要执行&#34; has_many至&#34;在这里,您可以使用根据相应约定命名的连接表来处理HABTM关系。