为has创建中间模型属于多个关联

问题描述 投票:-1回答:2

我有两个模型之间的has_and_belongs_to_many关系。

class DirectoryListing 
 has_and_belongs_to_many :directory_listing_categories

end

class DirectoryListingCategory
 has_and_belongs_to_many :directory_listings

end

这创建了两个表directory_listingsdirectory_listing_categories

还有一个名为directory_listing_categories_directory_listings的中间第三张表

我可以使用活动记录查询从控制台访问前两个表。由于此关系不会为中间第三个表创建第三个模型,因此我无法从rails控制台访问第三个中间表。

我尝试为此创建一个模型,但没有成功。

这是访问第三个表的正确方法吗?

class DirectoryListingCategoryDirectoryListing < ActiveRecord::Base

end
ruby-on-rails
2个回答
0
投票

首先,要在控制台中访问表,必须在应用程序中创建一个与表名相同的模型。

其次,如果要创建中间表的记录,则应通过在控制台中执行原始查询来创建它,

ActiveRecord::Base.connection.execute('your insert into query goes here')

0
投票

我最近创建了一个小应用程序,我必须存储一些角色并将它们映射到用户。设置是:

  1. User模型对应users表。
  2. Role模型对应roles表。
  3. 我需要一个表来执行多对多映射。

我写的用于创建关联表的迁移是这样的:

class CreateUserRoleJoinTable < ActiveRecord::Migration[5.2]
  def up
    create_join_table :users, :roles
  end

  def down
    drop_join_table :users, :roles
  end
end

当您运行迁移时,Rails创建了一个roles_users。如果需要,还可以在up方法中添加foreign_keys和唯一索引。

模型如下:

User

class User < ApplicationRecord
  has_and_belongs_to_many :roles
end

Role

class Role < ApplicationRecord
  has_and_belongs_to_many :users
end

所以它或多或少是同一种设置。

这个设置为我提供了以下用户对象的方法(由下面的user对象表示:

  1. user.role_ids:这将获取此用户与之关联的角色的角色ID。
  2. user.role_ids=:这将允许我使用赋值和数组插入为用户设置角色。像这样: user.role_ids = 1 # Assuming there are no roles already associated with the user user.role_ids = [2,6] # This will remove the previously assigned role (with ID = 1) and assign the roles with IDs 2 & 6 to the user user.role_ids << 5 # This will add the role ID 5 to the user (final role_ids at this point will be [2,5,6]
  3. user.roles:这与user.role_ids类似,但会获取Role对象而不是ID。
  4. user.roles=:再次,类似于user.role_ids=,但将采取对象而不是ID。

同样对于角色模型,我得到role.user_idsrole.user_ids=role.usersrole.users=

关键是 - 我很少,如果需要触摸roles_users表。

如果我这样做,我可以做一个User.connection.execute(sql)并手动阅读结果。否则,自动注入的方法就足够了。

我希望这有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.