问题
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