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.

On 5 Jun 2008, at 16:42, psyche wrote:

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?

On Jun 5, 7:51 pm, Thorsten M. [email protected]

Actually it was a bad example :slight_smile:

A have an User and Role model with has_and_belongs_to_many
relationship and I want to create named_scope for User model to
extract only “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’ })}

Rails generate 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 is users.role_id. Are there any methods to generate
only role_id?

On Jun 5, 7:51 pm, Thorsten M. [email protected]

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

2008/6/5 psyche [email protected]:

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.

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

2008/6/5 Kirill T. [email protected]: