On Sep 29, 2011, at 8:56 PM, maskiran wrote:

I have the following tables

create table files(id int ai pk, name varchar(255)
create table admins (file_id int, user_id int)
create table users (id int ai pk, name varchar(16),email varchar(255))

And presumably classes like:

class File
  has_many :admins
  has_many :users, :through => :admins
end
class Admin
  belongs_to :file
  belongs_to :user
end
class User
end


I want to get all the admin user names and emails of a given file. Say
for file 1

File.find(1).users

or

File.where(:id => 1).users


Admin.where(:file_id=>1).includes(:user). it works very good. Now I
want to sort the admins on the usernames

Then add and .order('users.name') to the query.

Alternatively, you could always get the users in that order:

class File
  has_many :admins
  has_many :users, :through => :admins, :order => 'users.name'
end


Admin.where(:file_id=>1).include(:user).order('users.name'). this
shows an sql query with an empty column and so bails out. here's the
query I got on the console

SELECT `admins`.`` AS t0_r0, `admins`.`file_id` AS t0_r1,
`admins`.`user_id` AS t0_r2, `users`.`id` AS t1_r0, `users`.`name` AS
t1_r1 FROM `admins` LEFT OUTER JOIN `users` ON `users`.`id` =
`admins`.`user_id` WHERE `admins`.`file_id` = 1 ORDER BY users.name

The first column name is being taken as empty (immediately after the
select).

Is this a bug? I don't want to have id field in the admins table as
that's not useful. How do I write a AR query to sort out this issue

thanks
Kiran


You should not need an `id` on the admins table, but you almost certainly want to have an index on each of the `file_id` and `user_id` columns.

-Rob

Rob Biedenharn          
r...@agileconsultingllc.com     http://AgileConsultingLLC.com/
r...@gaslightsoftware.com               http://GaslightSoftware.com/

--
You received this message because you are subscribed to the Google Groups "Ruby on 
Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to