找不到关联,Rails 3

pax*_*xer 5 activerecord ruby-on-rails

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
Run Code Online (Sandbox Code Playgroud)

和我的观点

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

我的视图上有下一个错误 - 无法找到关联:模型中的成员资格用户和我无法理解为什么会发生这种情况..

Sam*_*hie 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
Run Code Online (Sandbox Code Playgroud)

添加它,你应该启动并运行.