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