Ruby on Rails Thursday, July 30, 2015

I have a very simple question how can I convert mysql query as Raisl active record I am using find_by_sql but it only work for mysql when I move to heroku it doesn't work . Here is mysql query below .

   @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 to run it and no success . I have 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 above code is not generating the correct result here I have two models user and message their relation is user has_many messages and messages belons_to user When I am using this code I am getting this result in json format with no error .

[{"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 I am getting this result when I am using select function in this query is there anyone help me

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/fcc71be5-7d20-4362-bacf-c72357bebeb8%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment