【问题标题】:Rails has_many though association - specifying key nameRails has_many 虽然关联 - 指定键名
【发布时间】:2014-05-09 16:36:47
【问题描述】:

我有两个模型 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

企业所有者迁移:

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 会返回一个用户列表吗?

【问题讨论】:

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


    【解决方案1】:

    就我个人而言,我喜欢根据关联的表来命名关联,换句话说:user_id 而不是owner_id。而且由于您没有进行 HABTM 关系,因此您不受“buisinesses_owners”约定的约束,您可以为直通模型提供更好的名称,例如BusinessOwnership 甚至Ownership(例如,如果以多态方式用于任何所有权User 和另一个模型之间的关系)。

    请注意,直通模型中的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 模型,否则这里实际上不需要执行“has_many through”,您也可以使用join 处理HABTM 关系根据相应约定命名的表。

    【讨论】:

    • 这是我认为的答案 - 如果您需要,我可以解释为什么它有效
    • 很好的答案!我需要做什么才能使其与名为 :user_id 和“business_id”的 CreateBusinessOwnerships 列一起使用?
    • 就是这样:t.references :user 是一种更语义化的表达方式 t.integer :user_id
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多