find-by-sql

Is it possible to define a single SQL query that draws a set of permissible foreign_keys from one table and then uses them to filter another?

Specifically, I'm trying to figure out if it's possible to generate SQL that does what I want to feed into Ruby-on-Rails' find_by_sql method. Imagine there are Users, who are joined cyclically to other Users by a join table Friendships. Each User has the ability to create Comments. I'd like a SQL query to return the latest 100 comment...

Ruby on Rails: Instantiate associated models with find_by_sql?

Apparently, include and select can't be used simultaneously on a Rails find query, and this has been repeatedly marked as wontfix: http://dev.rubyonrails.org/ticket/7147 http://dev.rubyonrails.org/ticket/5371 This strikes me as very inconvenient, because the times I'd want to use include are exactly the same times I'd want to use select...

Ruby on Rails: Is it possible to :include the other leg of a circular join table?

I'm working on an application that models friendships between users. class User has_many :friendships has_many :friends, :through => :friendships, :conditions => "status = #{Friendship::FULL}" end class Friendship belongs_to :user belongs_to :friend, :class_name => "User", :foreign_key => "friend_id" end ...

is it possible to combine will_paginate with find_by_sql?

In my rails application I want to use will_paginate plugin to paginate on my query. Is that possible? I tried doing something like this but it didn't work: @users = User.find_by_sql(" SELECT u.id, u.first_name, u.last_name, CASE WHEN r.user_accepted =1 AND (r.friend_accepted =0 || r.friend_accepted IS NULL) ....

How to make activerecord use a field generated on the fly by find_by_sql

I'm using find_by_sql with Activerecord which I generate another field there that doesn't in the original table as a combination of different fields like: select (field1 + field2) as new_field_name If I try to access the newly generated field like: @user.new_field_name I get nothing! How do you suggest I should approach this proble...

ActiveRecord custom SQL in Ruby

I need to perform these SQL below, but I couldn't get the result. newid=Header.find_by_sql( "SELECT coalesce(max(transaction_id),0)+1 AS id FROM transaction_headers WHERE transaction_year = #{Time.now.year} AND transaction_type='#{fields[:transaction_type]}'" ) But I can't seem to get the result to newid. The only value I ...

sql left join where rails

Because I use rails I've become rusty on sql since I rarely use it in rails. I have two related tables: comments 1:m comment_views I want to find all comments where comment_views.viewed is false. Problem is, for some comments there is not a relating record in comment_views yet. So far I have select comments.id from comments ...