0

Models:

cities.rb:

has_many :cities_users
has_many :users, :through => :cities_users

I have a HABTM (through) between cities and users. I want to view all cities associated with a user. Here's what I have and what the error is:

users.rb

has_many :cities_users
has_many :cities, :through => :cities_users

Controller:

@user = User.find(current_user.id)
@users_cities = @user.cities

I have written a migration that creates the JOIN table:

create_table "cities_users", :id => false, :force => true do |t|
   t.integer "user_id"
   t.integer "city_id"
end

This is my error (relating to second line of controller code):

uninitialized constant User::CitiesUser

I'm having similar problems creating a city that is associated with a user too.

Many thanks.

ale
  • 11,636
  • 27
  • 92
  • 149

1 Answers1

0

You should create new model if you want to use has_many :through association.
Please, consider using has_and_belongs_to_many for direct many-to-many connection with no intervening model.

For any details you can read http://guides.rubyonrails.org/association_basics.html#choosing-between-has-many-through-and-has-and-belongs-to-many.

Sergey Alekseev
  • 11,910
  • 11
  • 38
  • 53