Rails 3 ActiveRecord where clause where id is set or null

∥☆過路亽.° 提交于 2020-01-04 10:42:52

问题


I have an ActiveRecord, Annotation, with two columns: user_id and post_id, which can be null. An annotation with null user_id and post_id are "global" annotations that are applicable to all posts across all users.

I would like to retrieve all annotations associated with a particular user's post AND all global annotations. In MySQL, the SQL command would be

select * from annotations where (user_id = 123 and post_id = 456) or (user_id is null and post_id is null)

In Rails 3, what is best way to code this as a Annotation.where clause?


回答1:


Unfortunately there is no really great way to use OR sql syntax. Your best two options are probably to write the where clause yourself using bound parameters:

annotations = Annotation.where("(user_id = ? and post_id = ?) OR (user_id is null and post_id is null)").all

Or you can dive into Arel and use that syntax to craft it (check out asciicast's Arel post).

Warning, everything in the or call is psuedocode, no idea how to do 'post_id is null' - you may have to just pass "user_id is null and post_id is null" to or(), but my best guess is:

annotations = Annotation.arel_table
annotations.where(annotations[:user_id].eq(123).
            and(annotations[:post_id].eq(456)).
            or(annotations[:user_id].eq(nil).and(annotations[:post_id].eq(nil))


来源:https://stackoverflow.com/questions/6336952/rails-3-activerecord-where-clause-where-id-is-set-or-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!