我需要在Event對象的2列中查找用戶標識,因此需要使用OR查詢。 做什麼是正確的方法?下面的代碼不起作用。Rails 4中的活動記錄或查詢
@event=Event.where((user_id= (current_user.id)) or (user2_id= current_user.id))
我需要在Event對象的2列中查找用戶標識,因此需要使用OR查詢。 做什麼是正確的方法?下面的代碼不起作用。Rails 4中的活動記錄或查詢
@event=Event.where((user_id= (current_user.id)) or (user2_id= current_user.id))
寫爲
@event = Event.where("user_id = :uid or user2_id = :uid", {uid: current_user.id})
您可以像使用
@event=Event.where("user_id= ? or user2_id = ?", current_user.id, current_user.id)
我建議有一個更好的數據庫結構,所以不要使用需要使用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)