Ruby on rails Rails如何创建多对多关系以及保存创建它的人
我有三种型号Ruby on rails Rails如何创建多对多关系以及保存创建它的人,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,我有三种型号 使用者 公司 标签 我想在用户和标签之间创建多对多关系,但我也想知道是哪个公司创建了这种关系,以便在数据库中按标签搜索用户时,系统只搜索公司分配的标签 我知道如何建立一个有很多关系 User has_many: tags, through: :user_tags has_many: user_tags Tag has_many: users, through: :user_tags has_many: user_tags UserTag belongs_to: user b
- 使用者
- 公司
- 标签
用户
和标签
之间创建多对多关系,但我也想知道是哪个公司
创建了这种关系,以便在数据库中按标签搜索用户时,系统只搜索公司分配的标签
我知道如何建立一个有很多关系
User
has_many: tags, through: :user_tags
has_many: user_tags
Tag
has_many: users, through: :user_tags
has_many: user_tags
UserTag
belongs_to: user
belongs_to: tag
但我不明白的是,如何存储谁创建了这种关系,然后再提取特定公司标记的所有用途
我非常感谢您在这方面提供的帮助。您可以将公司id字段添加到UserTag模型中,以表示创建此条目的公司。 然后,对于您的查询“当通过标签在数据库中搜索用户时,系统仅在公司分配的标签中搜索” 必需的标签id=分配必需的标签id 必需的\u公司\u id=分配\u必需的\u公司\u id user\u id=UserTag.where(tag\u id:required\u tag\u id)。where(company\u id:required\u company\u id)。pull(:user\u id) users=User.where(id:User\u id)
您可以将company_id字段添加到UserTag模型中,以表示创建此条目的公司。 然后,对于您的查询“当通过标签在数据库中搜索用户时,系统仅在公司分配的标签中搜索” 必需的标签id=分配必需的标签id 必需的\u公司\u id=分配\u必需的\u公司\u id user\u id=UserTag.where(tag\u id:required\u tag\u id)。where(company\u id:required\u company\u id)。pull(:user\u id) users=User.where(id:User\u id)
希望这对你有帮助
Class User < ActiveRecord::Base
has_many: tags, through: :user_tags
has_many: user_tags
Class Tag < ActiveRecord::Base
has_many: users, through: :user_tags
has_many: user_tags
end
Class UserTag < ActiveRecord::Base
belongs_to: user
belongs_to: tag
belongs_to :company
before_save :set_company
private
def set_company
self.company = "your logic for associating the company"
end
end
#migration for user_tags
create_table :user_tags do |t|
t.references :user
t.references :company
t.references :tag
end
for fetching users tagged with a specific tag by a specific company
UserTag.where(company_id: 'the company id', tag_id: 'the tag id').users
Class用户
希望这对你有所帮助
Class User < ActiveRecord::Base
has_many: tags, through: :user_tags
has_many: user_tags
Class Tag < ActiveRecord::Base
has_many: users, through: :user_tags
has_many: user_tags
end
Class UserTag < ActiveRecord::Base
belongs_to: user
belongs_to: tag
belongs_to :company
before_save :set_company
private
def set_company
self.company = "your logic for associating the company"
end
end
#migration for user_tags
create_table :user_tags do |t|
t.references :user
t.references :company
t.references :tag
end
for fetching users tagged with a specific tag by a specific company
UserTag.where(company_id: 'the company id', tag_id: 'the tag id').users
Class用户
多亏了看一看,我试着从中找出一些道理:)这看起来确实会有用多亏了看,我试着从中找出一些道理:)这看起来确实会有用work@Saadia酷。如果你还面临任何困难,请告诉我。@Saadia Cool。如果你还面临任何困难,请告诉我。