2010-12-04 57 views
5
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 

和我查看找不到关联,Rails 3的

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

我已经得到了我的下一篇错误 - 找不到关联:模型用户 成员,我不能明白这是为什么发生..

回答

15

你需要明确说明has_many :memberships,像这样:

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 

加入,你应该开始运行。

+0

谢谢,你是男人! – paxer 2010-12-04 08:27:46

0

我找到了原因,

我需要

has_many :memberships 

添加到我的用户和角色模型。

无论如何,谢谢! :)

+1

恩......桑姆里奇的回答已经说明了 – Zabba 2010-12-04 08:40:04