Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 具有自联接的模型的Habtm联接表_Ruby On Rails_Database_Ruby On Rails 4_Join - Fatal编程技术网

Ruby on rails 具有自联接的模型的Habtm联接表

Ruby on rails 具有自联接的模型的Habtm联接表,ruby-on-rails,database,ruby-on-rails-4,join,Ruby On Rails,Database,Ruby On Rails 4,Join,这是从我的 我有一个用户模型,有两个自连接,卖方和买方 我有一个类别模型,卖家有很多类别,买家也是。 我如何创建迁移,以便我可以执行seller.categories和categories.buyer等 我以为它会像我下面的东西,但它不工作 def change create_table :categories_sellers do |t| t.references :category t.references :user end add_fore

这是从我的

我有一个用户模型,有两个自连接,卖方和买方

我有一个类别模型,卖家有很多类别,买家也是。 我如何创建迁移,以便我可以执行seller.categories和categories.buyer等

我以为它会像我下面的东西,但它不工作

def change
    create_table :categories_sellers do |t|
      t.references :category
      t.references :user
    end
    add_foreign_key :categories_sellers, :users, column: :trainer_id
    add_index :categories_users, [:category_id, :seller_id]
    add_index :categories_users, :seller_id
    end
  end

要回答您的问题,您似乎只需要将t.references:user更改为t.references:seller

也就是说,我强烈建议将您的项目建模为:

module User
  extend ActiveSupport::Concern

  has_many :category_users, as: :user
  has_many :categories, through: :category_users

  # include any common methods for buyers and sellers, 
  # basically your current User model
end

class Buyer < ActiveRecord::Base
  include User
end

class Seller < ActiveRecord::Base
  include User
end

class CategoryUser < ActiveRecord::Base
  belongs_to :category
  belongs_to :user, polymorphic: true
end

class Category < ActiveRecord::Base
  has_many :category_users
  has_many :buyers, through: :category_users, source: :user, source_type: 'Buyer'
  has_many :sellers, through: :category_users, source: :user, source_type: 'Seller'
end
我没有亲自检查过,但应该是正确的,或者很接近。不过,总体原则是利用多态关联在“某种类型的用户”(无论是买家、卖家还是您提出的任何其他类型的用户)和类别之间建立更自然的关联。然后,您不需要反复复制相同类型的关联,因为模型略有不同

以下是有关此方法的更多详细信息:


您希望如何在加入表中对
卖家
买家
进行分类?当然你只需要
user\u id
category\u id
?我想我应该有两个单独的连接表,一个用于卖家/类别,另一个用于买家/类别,我需要能够找到特定类别的所有卖家,因此我认为连接表是正确的…不?我知道这并不能回答你的问题,但对于一个卖家来说,属于某个类别感觉很奇怪。产品不应该属于某个类别吗?建模可以简化,以便使用单表继承(STI)更容易处理此问题:
def change
  create_table :category_users do |t|
    t.references :category
    t.references :user, polymorphic: true
  end
  add_index :category_users, :category_id
  add_index :category_users, [:category_id, :user_id]
  add_index :category_users, [:category_id, :user_id, :user_type]
end