我有两个模型之间的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_listings
和directory_listing_categories
还有一个名为directory_listing_categories_directory_listings
的中间第三张表
我可以使用活动记录查询从控制台访问前两个表。由于此关系不会为中间第三个表创建第三个模型,因此我无法从rails控制台访问第三个中间表。
我尝试为此创建一个模型,但没有成功。
这是访问第三个表的正确方法吗?
class DirectoryListingCategoryDirectoryListing < ActiveRecord::Base
end
首先,要在控制台中访问表,必须在应用程序中创建一个与表名相同的模型。
其次,如果要创建中间表的记录,则应通过在控制台中执行原始查询来创建它,
ActiveRecord::Base.connection.execute('your insert into query goes here')
我最近创建了一个小应用程序,我必须存储一些角色并将它们映射到用户。设置是:
User
模型对应users
表。Role
模型对应roles
表。我写的用于创建关联表的迁移是这样的:
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和唯一索引。
模型如下:
class User < ApplicationRecord
has_and_belongs_to_many :roles
end
class Role < ApplicationRecord
has_and_belongs_to_many :users
end
所以它或多或少是同一种设置。
这个设置为我提供了以下用户对象的方法(由下面的user
对象表示:
user.role_ids
:这将获取此用户与之关联的角色的角色ID。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]
user.roles
:这与user.role_ids
类似,但会获取Role对象而不是ID。user.roles=
:再次,类似于user.role_ids=
,但将采取对象而不是ID。同样对于角色模型,我得到role.user_ids
,role.user_ids=
,role.users
,role.users=
。
关键是 - 我很少,如果需要触摸roles_users
表。
如果我这样做,我可以做一个User.connection.execute(sql)
并手动阅读结果。否则,自动注入的方法就足够了。
我希望这有帮助。