[英]Rails where clause for :through association
我有以下關聯...
class Event < ActiveRecord::Base
...
has_many :tags, :through => :taggings
這使我可以執行Event.last.tags之類的操作,並查看與電子郵件關聯的所有標簽。 我正在嘗試為標記提供一個where子句,我可以在其中執行類似的操作...
Event.where tag: 'my_tag'
當我這樣做時,我得到:
2.1.3 :020 > Event.where tags: 'test'
Event Load (0.4ms) SELECT `events`.* FROM `events` WHERE `events`.`tags` = 'test'
ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'events.tags' in 'where clause': SELECT `events`.* FROM `events` WHERE `events`.`tags` = 'test'
這是您要找的東西嗎:
Event.includes(:tags).where(tags: {name: 'my_tag'})
這將獲取所有帶有標簽名稱為'my_tag'
標簽事件。 使用您要為其運行查詢的tags
表中存在的適當列名更改name
。
您需要指定包含“ my_tag”的標簽記錄的字段。 例如,如果該字段稱為名稱,則:
Event.first.tags.where(name: 'my_tag')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.