[英]Rails 4 - helper method
I'm trying to figure out how to use a helper method I've written. 我试图弄清楚如何使用我编写的帮助方法。
It works fine in the profile model, however it isn't working as i want it to in the user model. 它在配置文件模型中工作正常,但是却无法如我所愿地在用户模型中工作。
I have models called user and role. 我有称为用户和角色的模型。 They are associated as has and belongs to many. 它们彼此关联并属于许多。
In my role helper, I have: 在我的角色助手中,我有:
module RolesHelper 模块RolesHelper
def text_for_role(name)
case name
when 'guest'
'Guest Pass'
end
end
In my user index show page I have: 在我的用户索引显示页面中,我有:
<% @users.each do |user| %>
<%= user.roles.each do |role| %>
<%= text_for_role(role.name)%>
<% end %>
</td>
When I try this, it renders: 当我尝试这个时,它呈现:
Guest Pass [#] 来宾通行证 [#]
How do i get rid of the bit inside the []? 我如何摆脱[]中的位? - I only want to show the role name. -我只想显示角色名称。
Change 更改
<%= user.roles.each do |role| %>
To 至
<% user.roles.each do |role| %>
module RolesHelper
@roles = {
'Guest' => 'Guest Pass',
'Admin' => 'Admin pass',
}
class << self
def list
@roles.map{|k,v| [k,v] }
end
def role(str)
return @roles[str]
end
end
end
Index page: 索引页:
<%= user.roles.each do |role| %>
<% RolesHelper.role(role)%>
<% end %>
Also if you do in users_controller.rb , that would load roles faster for each user. 同样,如果您在users_controller.rb中这样做,则将为每个用户更快地加载角色。
def index
@users = User.includes(:role)
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.