In the former case it works fine because, @user points to a userobject. Assuming that your user model has the following attributes(id, name, created_at, updated_at).
@user= User.find(current_user.id)
@user.class
=> User(id: integer, name: string, created_at: datetime, updated_at: datetime, etc)
@user
=> #<User id: 1, name: "Amar",created_at: "2013-07-10 10:07:37", updated_at: "2013-07-10 10:07:37">
So now your instance variable @user points to a userobject and so the following works.
@users_cities = @user.cities
But in case of where, it is a relation and the instance variable holds an array having a single record.
@user= User.where(:id => current_user.id)
@user.class
=> ActiveRecord::Relation
@user
=> [#<User id: 1, name: "Amar", created_at: "2013-07-10 10:07:37", updated_at: "2013-07-10 10:07:37">]
Here, @user is not pointing to a userobject and hence you cant get the cities assoicted with that user. You can try the following.
@user= User.where(:id => current_user.id).first #first gets the first object from the array.
@user.class
=> User(id: integer, name: string, created_at: datetime, updated_at: datetime, etc)
@user
=> #<User id: 1, name: "Amar",created_at: "2013-07-10 10:07:37", updated_at: "2013-07-10 10:07:37">
In this case the following should work because your instance variable @user have made to point to a single userobject by using first.
@users_cities = @user.cities
Again in your case, your are getting an array from User model
@other_users = User.where("id != ?", 1)
It will collect an array of elements. So you have to iterate over the array to find its cities.
@other_users.each do |user|
# do manipulation with user.cities
end
In this case if you use first then it will point only to the first object in the array. So iterate through it to cover all the other users.