考虑以下我的域模型的简化表示。
class Item < ApplicationRecord
has_many :tags
end
class Tag < ApplicationRecord
belongs_to :item
enum :value, %i{hot cold}
validates :value, uniqueness: { scope: :item_id }
end
每个项目都有零个或多个标签,这些标签指示可能与我的程序相关的项目属性。在此示例中,“热”和“冷”是唯一有效的标签。
如果我想找到所有标记为“热门”的项目,我可以写
Item.joins(:tag).where('tags.value = 0')
当然,我更喜欢写“hot”这个词,而不是枚举的整数值。我可以用命名参数来强制 ActiveRecord 的手。
Item.joins(:tag).where('tags.value': 'hot')
但是拥有一个名称不是有效 Ruby 标识符的命名参数感觉有点……错误。有没有一种更简洁的方法来进行此查询,而不涉及如此奇怪的伪变量?
这样感觉好点了吗:
Item.joins(:tag).where(tags: {value: :hot}})
或
class Item < ApplicationRecord
has_many :tags
scope :tagged, ->(value) { joins(:tags).where(tags: {value:}) }
end
Item.tagged(:hot)
首先问题中的代码是错误的。如果项目有很多标签,您需要使用此关联名称。
joins(:tags)
,不是joins(:tag)
。否则会出现错误
通常对于
where
中的连接表使用散列方法。键是表名,值是带有必要参数的哈希值
Item.joins(:tags).where(tags: { value: 'hot' })