0

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?

1 Answer 1

1

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(', ') %>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, the first line is what I was looking for! As a note, the table cities_users has date, name, and descr so it`s not a standard habtm.
In that case, I'd go with has_many :through and still use AR associations instead of querying against the cities_users table.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.