1

I am trying to specify the index view in my controller with a where or clause. Right now, the code is only returning the condition before the ||, if it finds that.

My code:

  def index
    @trades = Trade.where(grower_id: session[:user_id]) || 
    Trade.where(consumer_id: session[:user_id])
  end

I've tried:

@trades = Trade.where(grower_id: session[:user_id]).or(Trade.where(consumer_id: session[:user_id]))

and:

@trades = Trade.where(grower_id: session[:user_id])  ||=(Trade.where(consumer_id: session[:user_id]))

I also checked out this response, but those suggestions aren't working.

Any help would be greatly appreciated!

Community
  • 1
  • 1
  • Ruti Wajnberg, did my answer help? Let me know if you have any other question. – K M Rakibul Islam Nov 11 '15 at 18:14
  • Welcome to StackOverflow. When people answer your question and that solve your problem, you can accept the answer you like most. To know more about how accepting answers work, please see this post: http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – K M Rakibul Islam Nov 11 '15 at 18:14

1 Answers1

3

Active Record Query does not support or clause in Rails 4. But, it's coming in Rails 5. If you want to use or clause in your >= Rails 4.2 application for Active Record queries, you can use the where-or gem. Then, you can have your Active Record query like this:

@trades = Trade.where(grower_id: session[:user_id]).or(Trade.where(consumer_id: session[:user_id]))

To explain the behaviour of this code:

  def index
    @trades = Trade.where(grower_id: session[:user_id]) || 
    Trade.where(consumer_id: session[:user_id])
  end

|| (logical or operator) will look at the value of the first expression, if it's present i.e. if it's not nil or false, then will return the value. If not, only then it goes to the next expression to evaluate. That's why you are seeing that behavior which is expected. See this post for some more details on how logical or operator (||) works.

Now, to fix your problem, you can re-write your query using SQL:

def index
  @trades = Trade.where('trades.grower_id = ? OR trades.consumer_id = ?', session[:user_id], session[:user_id])
end

As mu is too short pointed in the comment section, to avoid repetition in your code, you can also write the query this way:

def index
  @trades = Trade.where('trades.grower_id = :user_id OR trades.consumer_id = :user_id', user_id: session[:user_id])
end
Community
  • 1
  • 1
K M Rakibul Islam
  • 33,760
  • 12
  • 89
  • 110
  • 2
    I'd recommend `Trade.where('trades.grower_id = :user_id OR trades.consumer_id = :user_id', :user_id => session[:user_id])` to avoid repetition. Actually, I'd recommend the named parameter style period. – mu is too short Nov 09 '15 at 01:17