【发布时间】:2015-07-26 17:09:45
【问题描述】:
在 Rails 4 中,我有一个带有 JSON 类型列的表。我有一个像这样效果很好的方法
def self.that_match_property(key: "default", value: "default")
where("properties ->> ? = ?", key, value)
end
所以对于Model.first.properties,我得到{"name": "Bill", "user_id": "1"}
我可以做到这一点。
Model.that_match_property(key: "name", value: "Bill")
我在我的 json properties 列中获得了与键/值对匹配的记录。
但是...假设我希望该值是一个 id 数组。所以我有...
user1.properties = {"name": "Bill", "user_id": "1"}
user2.properties = {"name": "Ted", "user_id": "2"}
user3.properties = {"name": "Rufus", "user_id": "3"}
现在我也有bill_and_ted_ids = ["1", "2"]
我希望能够做到这一点:
Model.that_match_property(key: "user_id", value: bill_and_ted_ids)
但这不起作用。通常我可以将一组 ID 传递给活动记录查询,然后它会转换为正确的 sql。
在 Rails 中使用 JSON 数据类型执行上述操作的正确方法是什么?
【问题讨论】:
标签: sql ruby-on-rails json postgresql activerecord