can i use OR and also AND in the same where clause?

27 views
Skip to first unread message

fugee ohu

unread,
Apr 7, 2016, 11:15:53 AM4/7/16
to Ruby on Rails: Talk
I need to select where column = (this||that) and someothercolumn=something

<% @friended = current_user.profile.friendables.where("(from_id = ? OR to_id = ?) AND accepted = true)", current_user.idcurrent_user.id) %>

Giedrius Rimkus

unread,
Apr 8, 2016, 4:45:42 AM4/8/16
to Ruby on Rails: Talk
You can achieve this with:

<% 
@friended = current_user.profile.friendables.where("from_id = :user_id OR to_id = :user_id", user_id: current_user.id).where(accepted: true)
%>

j...@room118solutions.com

unread,
Apr 12, 2016, 1:37:52 PM4/12/16
to Ruby on Rails: Talk
I like to use a dash of Arel for this (took a guess at the friendables association class name, adjust as necessary):

current_user.profile.friendables.where(Friendable.arel_table[:from_id].eq(current_user.id).or(Friendable.arel_table[:to_id].eq(current_user.id))).where(accepted: true)

A bonus is that this will qualify the from_id/to_id columns with the Friendable table name to avoid SQL errors if the column names clash with any other tables included in the query.

I'd also consider adding an accepted scope to friendables:

scope :accepted, -> { where accepted: true }

Then, you could do this:

current_user.profile.friendables.accepted.where(Friendable.arel_table[:from_id].eq(current_user.id).or(Friendable.arel_table[:to_id].eq(current_user.id)))

Jim
Reply all
Reply to author
Forward
0 new messages