考虑以下我的域模型的简化表示。
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
每个项目都有零个或多个标签,这些标签指示可能与我的程序相关的项目属性。在此示例中,“hot”和“cold”是唯一有效的标签。
如果我想找到所有标记为“热门”的项目,我可以写
Item.joins(:tags).where('tags.value = 0')
当然,我更喜欢写“hot”这个词,而不是枚举的整数值。我可以用命名参数来强制 ActiveRecord 的手。
Item.joins(:tags).where('tags.value': 'hot')
但是使用一个名称不是有效 Ruby 标识符的命名参数感觉有点……错误。有没有一种更简洁的方法来进行此查询,而不涉及如此奇怪的伪变量?
最佳答案
这感觉更好吗:
Item.joins(:tags).where(tags: {value: :hot})
或
class Item < ApplicationRecord
has_many :tags
scope :tagged, ->(value) { joins(:tags).where(tags: {value:}) }
end
Item.tagged(:hot)
关于ruby-on-rails - 引用连接 Rails 表中枚举的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76886845/