2

Is there a way to write it in a more 'Rails-friendly' way?

i.e. if I were searching for anyone of those attributes, I would just do Feedback.where(:poster_id => 3) and it would be good.

But how do I achieve the OR in the Rails 3 friendly syntax (as opposed to the SQL friendly one).

Also, if it is better to use my original one over the desired one, why is it better?

Thanks.

Edit 1: Btw, if I do Feedback.where(:poster_id => 3, :receiver_id => 3) that returns the result for the AND operation, which is the exact opposite of what I want. So I feel so close, just not quite there.

marcamillion
  • 32,933
  • 55
  • 189
  • 380

1 Answers1

2

You can do this by putting SQL fragments in the where() arguments. For more information you can look at the ActiveRecord querying guide.

Feedback.where("poster_id = ? OR receiver_id = ?", 1, 3)

You can do this without SQL fragments as described in this SO post:

t = Feedback.arel_table
Feedback.where(t[:poster_id].eq(1).or(t[:receiver_id].eq(2)))
Community
  • 1
  • 1
Spike Gronim
  • 6,154
  • 22
  • 21
  • That's the same thing as my original statement, imho...if not worse - in terms of extra execution needed at the application level. – marcamillion Oct 04 '11 at 01:12
  • I guess I don't understand the question. I thought you were asking how to use an OR condition with ActiveRecord 3. What is your actual question? What extra execution is needed at the application level? – Spike Gronim Oct 04 '11 at 15:36
  • Well I guess a more specific question would be how can I use an `OR` condition without using SQL fragments? – marcamillion Oct 04 '11 at 17:52
  • Ok...will stick with the SQL then. The other way feels messy :) – marcamillion Oct 05 '11 at 02:37