Victor Pudeyev
Victor Pudeyev

Reputation: 4538

how to display associated models in views in ruby on rails

This is probably a n00b question. I have CitiesUser model:

class CitiesUser < ActiveRecord::Base { belongs_to :city belongs_to :user }

In the controller I do this:

def index { @cities_users = CitiesUser.find(:all, :conditions => { :user_id => session[:user][:id] }, :include => [:city])

and in the view this:

<%= @cities_users.inspect %>

Now, I don't see associated model City anywhere. How do I iterate in my view over Cities that are attached to CitiesUser?

My WEBRick says:

CitiesUser Load (0.6ms) SELECT "cities_users".* FROM "cities_users" WHERE "cities_users"."user_id" = 1

City Load (0.8ms) SELECT "cities".* FROM "cities" WHERE ("cities"."id" IN (5,3))

So the association is being loaded, right? Which variable is it stored in, or how to I put it inside my CitiesUser?

Upvotes: 0

Views: 1927

Answers (1)

Jeremy Weathers
Jeremy Weathers

Reputation: 2554

You have to go through the city association.

<%= @cities_users.map{ |cu| cu.city.name }.sort.join(', ') %>

However, if the cities_user table is basically [ :user_id, :city_id ], then you have no need for the CitiesUser model at all. Instead your models should look like:

class City < ActiveRecord::Base
  has_and_belongs_to_many :users
end

class User < ActiveRecord::Base
  has_and_belongs_to_many :cities
  ...
end

In your controller, just make sure you have the User record (many auth schemes make this avaiable via a current_user method:

@user = current_user
@user ||= User.find session[:user][:id]

Then in your view:

<%= @user.cities.map { |c| c.name }.sort.join(', ') %>

Upvotes: 1

Related Questions