0

I have a user table and address table. A user has many addresses. So my model structure is

class User < ActiveRecord::Base
  has_many :addresses
end

class Address < ActiveRecord::Base
  belongs_to :user
end

I want to show user information along with user country code. Since I used includes to avoid n+1

User.where(:active => true).includes(:addresses)
SELECT "users".* FROM "users" where active=true
SELECT "addresses".* FROM "addresses" WHERE "addresses"."user_id" IN (1, 2)

Here I get users along with addresses as expected. But in my scenario, I don't want to get all the addresses fields from DB. Only country_code is enough from address object as I don't want to consume more memory. So my second query would be good if its like

 SELECT "addresses"."country_code" FROM "addresses" WHERE "addresses"."user_id" IN (1, 2)

Can we apply select option to address query in the above scenario?

Selvamani
  • 7,434
  • 4
  • 32
  • 43

1 Answers1

0

you can not direct access of includes table record so you need to create an array of record for this. than for this use an association to get access data of second model. like this.

on your model or controller user like this

@users_addresses = User.where(:active => true).includes(:addresses)

than use on your view to access data of address model like this

<% @users.each do |u|  %>
   <% u.addresses.try(:country_code)%>
<% end %>
VijayGupta
  • 637
  • 3
  • 11