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?
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:
Or you can dive into Arel and use that syntax to craft it (check out asciicast’s Arel post).
Warning, everything in the
orcall 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” toor(), but my best guess is: