has_many associations table confusing-Collection of common programming errors
My goal here is to print list of users from specified city and category with their names, address and club name.Name and address display correctly but when i add club name,says undefined method memberships for #
.I know this is because Club is in different model ,So the question is how do i access club name?I am really shallow in complex has_many realtionships.Can anybody make necesary corrections please,This is how far i got.Thank you in advance
MODELS
class User < ActiveRecord::Base
has_many :memberships
has_many : clubs,:through =>:memberships
belongs_to :category
belongs_to :city
end
class Club < ActiveRecord::Base
has_many :users
has_many :memberships
has_many : users ,:through =>:memberships
belongs_to :city
end
class Membership < ActiveRecord::Base
belongs_to :user
belongs_to :club
end
class City < ActiveRecord::Base
has_many :clubs
has_many :users
end
class Category < ActiveRecord::Base
has_many :users
end
CONTROLLER
@users=User.where("category_id =? AND city_id=?",Category.find(2),session[:city_id])
@[email protected]
@[email protected] #this gives undefined method membership
VIEW
#attribute name is in the club model not membership
ROUTE
devise_for :users
resources :city,:club,:category
-
The line below returns an array instead of what you are expecting, i.e. User object.
@[email protected]
If users shown in the view belong to different clubs you should access them directly in the view. You can eager load the clubs if needed.
In your controller
@users=User.where(:category_id => Category.find(2), :city_id=>session[:city_id]). include(:clubs)
In your view
-
First of all, you have an error in Club class. You cant have 2 relations with the same name. Second one will override first.
has_many : users ,:through =>:memberships
should be
has_many :members, :through =>:memberships, :foreign_key => 'user_id'
The search should be:
@users = User.where(:category_id => 2, :city_id => 3).include(:clubs)
Or whatever it values you want to search by.The view is:
#attribute name is in the club model not membership
Your routes are fine.
Originally posted 2013-11-09 22:49:54.