2014-09-21 70 views
0

我需要在Event對象的2列中查找用戶標識,因此需要使用OR查詢。 做什麼是正確的方法?下面的代碼不起作用。Rails 4中的活動記錄或查詢

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

回答

1

寫爲

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

您可以像使用

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

我建議有一個更好的數據庫結構,所以不要使用需要使用user#{N}_id找到用戶。

大概我會把你的桌子分成兩塊,每塊桌子都有user_id。你可以粘貼一些代碼,所以我可以幫你。

第二點,似乎模型操作目前在Controller中完成,您可能需要將業務邏輯移入模型中。

回答你的問題,你可以這樣做:

 
    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) 

來源: http://apidock.com/rails/ActiveRecord/Core/connection

0

如果你的目標是爲Rails 5可以使用OR作爲記錄here

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

你不不需要等待導軌5使用這個OR查詢。我們還可以使用它rails 4.2,感謝寶石where-or