select records from different model

Hi!

I'm new to the ruby on rails and have a question about find_by_sql method. I have two model A and B and I want to select all records from B with the A model. The following code: A.find_by_sql("select * from B") returns nothing. Are there any methods to do it?

Thanks.

Hi!

I'm new to the ruby on rails and have a question about find_by_sql method. I have two model A and B and I want to select all records from B with the A model. The following code: A.find_by_sql("select * from B") returns nothing.

Foo.find_by_sql returns instances of Foo. What are you trying to do ?

Fred

oops thats very un-rails :wink: (but should work)

first: are those tables related? Or why do you want to use A to retrieve B???

however why don't you use

B.find(:all)

Thanks for your comments. Actually it was a bad example :slight_smile:

I have a User and Role models with has_and_belongs_to_many relationship. I want to create named scope for admin users.

Something like this: named_scope :admin, :joins => "LEFT JOIN roles_users ON roles_users.user_id=users.id", :conditions => { :role_id => Role.find(:first, :conditions => { :name => 'admin' })}

But Rails returns the following sql: SELECT * FROM `users` LEFT JOIN roles_users ON roles_users.user_id=users.id WHERE (`users`.`role_id` = 1)

The bad thing: `users`.`role_id`. Are there any method to get `role_id` only?

I do not know is it a hack or a solution: User.scoped :joins => "LEFT JOIN roles_users ON roles_users.user_id=users.id WHERE role_id = {Role.find(:first, :conditions => { :name => "admin" }, :select => :id).id}"

Hope it helps somebody.

With "Role.find(:first..." I have two queries, but if admin role_id would determined in the spec it would be only one query.

Using named_scope it would only one query (truthly: only one additional query on startup). Cool! :slight_smile:

ActiveRecord::Base.connection.select_all("select * from users") returns all rows.