我有以下关联...
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'
.更改 name
使用存在于 tags
中的适当列名您尝试为其运行查询的表。
关于ruby-on-rails - :through association 的 Rails where 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26917077/