Replacing the ID with the value

Hi. I have a project based on Rails 3.0.3 and MySQL.

There are 2 tables (not all columns shown):

  1. users (id, name, group_id)

class User < ActiveRecord::Base
belongs_to :groups
end

  1. groups (id, name)

class Group < ActiveRecord::Base
has_many :users
end

Console output:

irb(main):001:0> User.first
=> #<User id: 1, name: “John S.”, group_id: 3>

How can i do that besides the “group_id: 3” result the query will
return the Group name too. For example:

irb(main):001:0> User.first
=> #<User id: 1, name: “John S.”, group_id: 3, group:
“Administrator”>

I can do this by using the JOIN statement in mysql, but i need to use
raw sql queries. May be there is a way to do it by using ActiveRecord
style ?

On 17 February 2011 21:50, jsmax [email protected] wrote:

irb(main):001:0> User.first
=> #<User id: 1, name: “John S.”, group_id: 3>

How can i do that besides the “group_id: 3” result the query will
return the Group name too. For example:

Have a look at the documentation:
http://ar.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

“Eager loading” is probably your friend, but you can also do what you
want by changing the :select option of any AR query.

On 17 February 2011 21:50, jsmax [email protected] wrote:

Hi. I have a project based on Rails 3.0.3 and MySQL.

There are 2 tables (not all columns shown):

  1. users (id, name, group_id)

class User < ActiveRecord::Base
belongs_to :groups

That should be :group (singular), user belongs to one group so singular.

irb(main):001:0> User.first
=> #<User id: 1, name: “John S.”, group_id: 3>

How can i do that besides the “group_id: 3” result the query will
return the Group name too. For example:

You can just say
User.first.group.name
or
user = User.first
group_name = user.group.name

Rails will fetch the group from the database when you reference it.
Alternatively you may use the :include option on find to force it to
fetch the user and group in one query if you are running into
performance problems.

Colin

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs