jsmax
(jsmax)
February 17, 2011, 9:50pm
1
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
2. groups (id, name)
class Group < ActiveRecord::Base
has_many :users
end
Console output:
irb(main):001:0> User.first
=> #<User id: 1, name: "John Smith", 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 Smith", 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 ?
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.
Colin_Law1
(Colin Law)
February 18, 2011, 9:51am
3
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.
end
2. groups (id, name)
class Group < ActiveRecord::Base
has_many :users
end
Console output:
irb(main):001:0> User.first
=> #<User id: 1, name: "John Smith", 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