Could not find the association, Rails 3

﹥>﹥吖頭↗ 提交于 2020-01-03 15:17:33

问题


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 ..


回答1:


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.




回答2:


I found the reason,

I'll need to add

has_many :memberships

to my User and Role models.

Thanks anyway ! :)



来源:https://stackoverflow.com/questions/4352595/could-not-find-the-association-rails-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!