Sachin Prasad
Sachin Prasad

Reputation: 5411

Convert simply mysql query to rails Active record

I have this query in MySQL and I need to convert this to rails active record:

select p.*,x.* from
(select * from users  ,roles_users
 where users.id=roles_users.user_id and roles_users.role_id not in(2,3)) as P
left join  
(select * 
  from cad_dispaths as T
 where `startdate_dispatch` = 
       ( select max(`startdate_dispatch`)
           from cad_dispaths
          where users_id = T.users_id ))  x 
on   x.users_id = p.user_id      

Upvotes: 1

Views: 1015

Answers (1)

heartpunk
heartpunk

Reputation: 2275

I think the best solution in this case is to use find_by_sql. An important caveat is that it is designed to work with fetching one kind of thing at a time. I don't know the semantics of your application, so I can't say if that's what this query is doing, but it seems like it might not be.

For example, you could do:

User.find_by_sql(your_sql)

Which would return a collection of user objects that satisfy that query. Any extra data, as of the last time I tried something like this (rails 2.3.x) would be shoved into attributes in each object in the collection. Pretty ugly, but it can be prettier than the alternatives, sometimes.

Upvotes: 2

Related Questions