How to convert mysql query to Rails ORM?

I have a very simple question, how can I convert the mysql query as an active Raisl record, I am using find_by_sql, but it only works for mysql, when I go to hero it does not work. Below is the mysql query.

   @message3 = User.find_by_sql("SELECT u.id,c.m_id,u.name,u.email
         FROM messages c, users u
         WHERE CASE 
         WHEN c.user_one = #{current_user.id}
         THEN c.user_two = u.id
         WHEN c.user_two = #{current_user.id}
         THEN c.user_one= u.id
         END 
         AND (
         c.user_one ='1'
         OR c.user_two ='1'
         )
         Order by c.m_id DESC Limit 20")

      

I have tried different rules for starting and without success. I used this code below:

   @m1 = Message.joins(:user).select("users.id,messages.m_id,users.name,users.email
,CASE WHEN messages.user_one =#{current_user.id} THEN messages.user_two =users.id WHEN messages.user_one =users.id THEN messages.user_two =1 END").where("messages.user_one = 1 OR messages.user_two = 1 ").limit(20).order(:m_id)

      

But the above code does not generate the correct result, here I have two user models and a message their relationship user has_many messages and user belons_to messages When I use this code, I get this result in json format without errors.

[{"m_id":55,"id":55,"name":"Example  User","email":"nilay@jumpbook.in","CASE WHEN messages.user_one =1 THEN messages.user_two =users.id WHEN messages.user_one =users.id THEN messages.user_two =1 END":0}]

      

How can I use this query perfectly and why am I getting this result when I use the select function in this query, is there anyone there to help me.

+3


source to share





All Articles