开发者

has_many associations table confusing

开发者 https://www.devze.com 2023-04-13 07:42 出处:网络
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 member

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 #<Enumerator:0xa5509b0>.I know this is because Club is in different model ,So the question is how do i access club name?I am really shallo开发者_JAVA百科w 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])
  @user=@users.collect
  @club=@user.memberships #this gives undefined method membership

VIEW

    <% @user.each do |user| %>
   <%= user.username %>
   <%= user.address %>
   <%= @club.name %> #attribute name is in the club model not membership
   <%end%>

ROUTE

       devise_for :users
      resources :city,:club,:category


The line below returns an array instead of what you are expecting, i.e. User object.

@user=@users.collect

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

<% @users.each do |user| %>
  <%= user.username %>
  <%= user.address %>
  <% user.clubs.each do |club| %>
    <%= club.name %>
  <%end%>  
<%end%>


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:

<% @user.each do |user| %>
  <%= user.username %>
  <%= user.address %>
  <%= user.club.name %> #attribute name is in the club model not membership
<%end%>

Your routes are fine.

0

精彩评论

暂无评论...
验证码 换一张
取 消