Ruby on rails Rails:多对多关系设置(ActiveRecord和ActiveAdmin)
我在产品和品牌表/模型之间添加了一个has_和won to_ 这是模型的外观:Ruby on rails Rails:多对多关系设置(ActiveRecord和ActiveAdmin),ruby-on-rails,activerecord,many-to-many,associations,activeadmin,Ruby On Rails,Activerecord,Many To Many,Associations,Activeadmin,我在产品和品牌表/模型之间添加了一个has_和won to_ 这是模型的外观: class Brand < ActiveRecord::Base has_and_belongs_to_many :products default_scope { order('name asc')} end class Product < ActiveRecord::Base has_and_belongs_to_many :brands end 联接表数据库迁移: class Cr
class Brand < ActiveRecord::Base
has_and_belongs_to_many :products
default_scope { order('name asc')}
end
class Product < ActiveRecord::Base
has_and_belongs_to_many :brands
end
联接表数据库迁移:
class CreateJoinTableProductsBrands < ActiveRecord::Migration
def change
create_join_table :products, :brands do |t|
t.integer :product_id
t.integer :brand_id
t.index [:product_id, :brand_id]
t.index [:brand_id, :product_id]
end
end
end
class CreateJoinTableProductsBrands
问题:
我强烈建议阅读一些教程和文档,解释ActiveRecord中HATBM或HMT关系的根本区别。我认为这将大大有助于回答你自己的问题 以下表为例:团队和用户(可能相当于您的品牌和产品)。它们之间同样存在着双向HATBM关系
create_table "teams", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "wins"
t.float "win_percentage"
end
create_table "teams_users", id: false, force: :cascade do |t|
t.integer "team_id", null: false
t.integer "user_id", null: false
end
add_index "teams_users", ["team_id", "user_id"], name: "index_teams_users_on_team_id_and_user_id", using: :btree
add_index "teams_users", ["user_id", "team_id"], name: "index_teams_users_on_user_id_and_team_id", using: :btree
create_table "users", force: :cascade do |t|
t.string "first_name"
t.string "last_name"
t.string "user_name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
请注意,teams表中没有用户id的外键(FK),users表中也没有FK。联接表的目的是联接这两个模型,因此每个模型中都不需要FK来链接它们
要回答前3个问题:
- 我不会将product_id列更改为数组。根本没有必要。这就是联接表的用途
- 我不会在产品中添加品牌标识栏。改用联接表
- 除非您有特定的理由需要ProductBrand型号,否则您不需要它。如果确实需要,那么我会提倡通过关系使用
have\u many。遵循Rails惯例,如果使用ActiveRecord的HATBM关联,您不需要/不想要这个
完全同意您的策略,但为了完全符合Rails惯例,您可能希望将联接表重命名为具有Teammember模型的teammembers。我已搜索了有关此的更多信息,但找不到任何信息-请您在文档中为我指出正确的方向好吗?是的,这纯粹是基于意见的。但根据我的经验,清晰地命名模型有助于其他人更好地理解您的代码。它还使代码更易于阅读。在你的例子中,模型需要命名为TeamsUser,对我来说,它有一个复数和单数部分的奇怪组合。但您的解决方案是完全有效和正确的!
create_table "teams", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "wins"
t.float "win_percentage"
end
create_table "teams_users", id: false, force: :cascade do |t|
t.integer "team_id", null: false
t.integer "user_id", null: false
end
add_index "teams_users", ["team_id", "user_id"], name: "index_teams_users_on_team_id_and_user_id", using: :btree
add_index "teams_users", ["user_id", "team_id"], name: "index_teams_users_on_user_id_and_team_id", using: :btree
create_table "users", force: :cascade do |t|
t.string "first_name"
t.string "last_name"
t.string "user_name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end