paxer
paxer

Reputation: 981

Could not find the association, 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've got next error on my View - Could not find the association :memberships in model User and i can't understand why this is happens ..

Upvotes: 5

Views: 2409

Answers (2)

paxer
paxer

Reputation: 981

I found the reason,

I'll need to add

has_many :memberships

to my User and Role models.

Thanks anyway ! :)

Upvotes: 0

Sam Ritchie
Sam Ritchie

Reputation: 11038

You need to explicitly state has_many :memberships, like this:

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 that in, and you should be up and running.

Upvotes: 16

Related Questions