Lets take the following example. We have two models with this association
class Post < ActiveRecord::Base
belongs_to :user
end
class User < ActiveRecord::Base
has_many :posts
end
So as you know, we can do the following:
<%= @post.title %>
<%= @post.user.name %>
etc etc
This association usually generates the following queries:
SELECT * FROM `posts` WHERE `post`.`id` = 1;
SELECT * FROM `users` WHERE `user`.`id` = 15; # from @post.user
Now if I want to select some specific fields (lets assume for a moment there's no association) when listing all posts or show just a single one, I do something like this:
@posts = Post.select("id, title, slug, created_at").all()
# or
@post = Post.select("id, title, slug, created_at").find(1)
In case of association how can I select specific fields for the associated query? In other words instead of having
SELECT * FROM `users`
SELECT * FROM `posts` WHERE `user_id` IN ( user IDs here )
to have
SELECT `id`, `name` FROM `users`
SELECT `id`, `user_id`, `title`, `slug` FROM `posts` WHERE `user_id` IN ( user IDs here )