У меня есть этот sql:
select al.name, date_trunc('day', rc.start_date) as d, min(rc.start_date)
from
records rc inner join relations rl
on rl.record_id=rc.id
inner join
aliases al on rl.alias_id=al.id
where rc.user_id=2 and ( al.contact_id<>2 or al.contact_id is null)
group by al.name, d
order by d DESC
И модели:
class Alias < ActiveRecord::Base
belongs_to :contact
has_many :relations, :dependent => :destroy
has_many :records, :through => :relations
belongs_to :user
end
class Record < ActiveRecord::Base
has_many :relations, :dependent => :destroy
has_many :aliases, :through => :relations
belongs_to :user
end
class Relation < ActiveRecord::Base
belongs_to :record
belongs_to :alias
end
class Contact < ActiveRecord::Base
has_many :aliases
belongs_to :user
end
class User < ActiveRecord::Base
has_many :aliases
has_many :contacts
has_many :records
end
Как мне написать SQL-запрос, представленный в виде рельсов?