electrify
electrify

Reputation: 155

Active Record OR query in Rails 4

I need to find user id in 2 columns of Event object so need to use OR query. What is the correct way to do it? The code below doesn't work.

@event=Event.where((user_id= (current_user.id)) or (user2_id= current_user.id))

Upvotes: 0

Views: 224

Answers (4)

Paulo Fidalgo
Paulo Fidalgo

Reputation: 22296

If you are aiming for Rails 5 you can use OR as documented here

Post.where("id = 1").or(Post.where("id = 2"))
# SELECT `posts`.* FROM `posts`  WHERE (('id = 1' OR 'id = 2'))

You don't need to wait for rails 5 to use this OR query. We can also used it with rails 4.2, thanks to gem where-or

Upvotes: 0

Dan Myasnikov
Dan Myasnikov

Reputation: 158

I would suggest to have a better database structure, so you don't use need to use user#{N}_id to find users.

Presumably, I would split the table you have into two, where each table has user_id. You can paste some code, so I can help you with that.

The second point, it seems that model operations are currently done in Controller, you might want to move Business logic into the model.

Answering your question, you can do:

  current_user_id = current_user.id
  query = "select * from events where user_id = #{current_user_id} or user2_id = #{current_user_id}"
  result = Event.connection.execute(query)

Source: http://apidock.com/rails/ActiveRecord/Core/connection

Upvotes: 2

Arup Rakshit
Arup Rakshit

Reputation: 118271

Write as

@event = Event.where("user_id = :uid or user2_id = :uid", {uid: current_user.id})

Upvotes: 1

Rahul Dess
Rahul Dess

Reputation: 2587

You can use like

@event=Event.where("user_id= ? or user2_id = ?", current_user.id, current_user.id)

Upvotes: 6

Related Questions