user4965201
user4965201

Reputation: 973

Rails 4 issue in includes and fetch associated items

I have an issue with the includes method in Rails. I have this user model:

class User < ActiveRecord::Base
  has_one :account
end

And this account model:

 class Account < ActiveRecord::Base
      belongs_to :User
    end

Now the user model has :id and :names and the account model has :user_id and :country

In another controller i want to fetch and display all the user names with their countries.

I am using this query

@users = User.includes(:account).where(some condition)

Please tell me what can I add in the query to fetch all the countries associated with the user names? Thanks in advance

Upvotes: 0

Views: 54

Answers (3)

Lakshmi Narayana
Lakshmi Narayana

Reputation: 88

Whenever we are using includes it by default does an outer join, so there will may be users who does not have any account and you will get error while trying to access user.account.country as user.account is nil and on the nil object it will try to call country method which does not exist.

Upvotes: 0

Athar
Athar

Reputation: 3268

user should be plural in the controller as you are getting list of records . like this

 @users = User.includes(:account)

in view you can do this.

<% @users.each do |user| %>
  <%= user.names %>
  <%= user.account.country %>
<% end %>

As names is user attribute, you can fetch directly, while country is account's attribute, you can fetch using user.account.country

Upvotes: 2

Gaurav Mamidwar
Gaurav Mamidwar

Reputation: 338

If it gives you error like NoMethodError (undefined method `account' for #) then this means you are converting it into an array in controller itself.

Change your code eg:

@users = User.includes(:account).where('id < 5')

And in View

<% @users.each do |user| %>
  <%= user.name %>
  <%= user.account.country %>
<% end %>

Upvotes: 1

Related Questions