view role titles of the user through assignment table
Hey I hope you 开发者_开发知识库can help me here.
I got a Role model:
has_many :users, :through => :role_assignments
has_many :role_assignments
a role assignment model:
belongs_to :user
belongs_to :role
and a user model:
has_many :roles, :through => :role_assignments
has_many :role_assignments
I want to display the users roles in a view.
I tried some stuff like: user.roles.names
but it didnt work
Since user.roles is an collection (array) of roles, you can't call names directly. Now I assume that the attribute you want to access is name so in that case you could do:
user.roles.map(&:name).join(", ")
which will collect all the names from the roles and then join them into a string seperated by commas. That is very simple and not very flexible. If you instead want to style it in some way you could do like this:
<% user.roles.each do |role| %>
<p>Role: <%= role.name %></p>
<% end %>
精彩评论