2017-07-14 42 views
0

我有3種型號的Rails如何創建一個多對多的關係,也節省誰創造了它

  • 用戶
  • 公司
  • 標籤

我想創建一個多到UserTags之間的很多關係,但我也想知道哪個Company創建了這種關係,以便當用戶在數據庫中通過標籤搜索到用戶時系統僅在公司分配的標籤中進行搜索。

我知道如何創建的has_many關係

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 

但我不明白的是如何儲存誰創造了這個關係,再後來拉由特定公司所標記的所有用途。

我真的很感謝這方面的幫助。

回答

1

您可以將company_id字段添加到UserTag模型以表示哪個公司創建此條目。 然後針對您的查詢

required_tag_id = assign_required_tag_id

required_company_id = assign_required_company_id

user_ids「當用戶通過標籤搜索數據庫系統僅由公司指派標籤搜索」 = UserTag.where(tag_id:required_tag_id).where(company_id:required_company_id).pluck(:user_id)

users = User.where(id:user_ids)

+0

感謝看看,我想一些弄明白這些:)這看起來像的東西,將工作 – Saadia

1

希望這可以幫助你

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 
+0

非常感謝,我期待到這個 – Saadia

+0

@Saadia酷。如果您仍然遇到任何困難,請告訴我。 –

相關問題