Could not find a link, Rails 3

class Membership < ActiveRecord::Base
  belongs_to :role
  belongs_to :user
end

class User < ActiveRecord::Base
   has_many :roles, :through => :memberships
end

class Role < ActiveRecord::Base
  has_many :users, :through => :memberships
end

and my view

<% for role in Role.find(:all) %>
      <div>
        <%=check_box_tag "user[role_ids][]", role.id, @user.roles.include?(role) %>
        <%=role.name%>
      </div>
     <% end %>

I have the following error in my view - Could not find an association: membership in the User model and I can not understand why this is happening.

+5
source share
2 answers

You need to explicitly specify has_many :memberships, for example:

class User < ActiveRecord::Base
   has_many :memberships
   has_many :roles, :through => :memberships
end

class Role < ActiveRecord::Base
   has_many :memberships
  has_many :users, :through => :memberships
end

Add this and you should be up and running.

+15
source

I found a reason

I need to add

has_many :memberships

for my User and Role models.

Thank you anyway!:)

0
source

All Articles