Ruby on Rails Friday, July 31, 2015

The table structure of the message table had these fileds m_id as primary key and user_one and user_two and created at and updated at these are the fields in my Table When I am using find_by_sql it work perfect but when I am using active record only then I am getting the problem I need a proper result how can I convert this find_by_sql query in Active record .

On Friday, July 31, 2015 at 11:23:08 AM UTC+5:30, nilayy...@gmail.com wrote:

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/41bc594b-c3af-40a1-96b8-4b75aaa73c9e%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment