Rails 4-如何在索引视图中使用辅助方法 [英] Rails 4 - how to use a helper method in an index view

查看:90
本文介绍了Rails 4-如何在索引视图中使用辅助方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试在索引视图中使用辅助方法时,我陷入了困境.

I'm getting stuck in trying to use a helper method in my index view.

在我的索引中,我有以下视图:

In my index, I have this view:

<% policy_scope(Article).sort_by(&:created_at).in_groups_of(2) do |group| %>

  <% group.compact.each do |article| %>
     <h4><%= link_to article.title, article  %></h4>
     <small><%= state_notice(article) %></small><br>
     <small><%= truncate(article.body, :ommission => "...", :length => 250) %></small>
     <%= link_to 'READ MORE', article_path(article), :class=>"portfolio-item-view" %>

以下行:<%= text_for_state(article)%>
在我的文章助手中有一个助手方法,如下:

The line that is:<%= text_for_state(article) %>
has a helper method in my articles helper as:

 module ArticlesHelper

    def state_notice(article)
      if current_user = article.user
           article.text_for_state(current_state) 
        elsif article.to_be_reviewed and current_user.has_role?(:org_approver)
           article.text_for_state(current_state) 
        else
            'test'
        end  
    end     

        def text_for_state(current_state)
      case current_state
      when 'draft'
        'Private draft'
      when 'review'
        'Under pre-publication review'
      when 'reject'
        'This article has not been approved for publication'

      when 'approve'
        'This article has been approved for publication'

      when 'publish'
        'Published'

      when 'remove'
        'Removed from publication'
      end
    end

end

"to_be_reviewed"方法在我的文章政策中定义(我使用pundit).

the method 'to_be_reviewed' is defined in my articles policy (I use pundit).

我希望索引视图可以评估用户是否应该为助手中列出的3种情况之一获取文本.相反,我收到一条错误消息,内容为:

I expect the index view to evaluate whether the user should get text for one of the 3 cases set out in the helper. Instead, I get an error message that says:

undefined local variable or method `current_state' for #<#<Class:0x007fba81f217a8>:0x007fba8651f390>
Did you mean?  current_user

.

有人可以看到我哪里出问题了吗?

Can anyone see where I've gone wrong?

推荐答案

尝试以下操作.

def state_notice(article)
  if current_user = article.user
    article.text_for_state(article.current_state)
  elsif article.to_be_reviewed and current_user.has_role?(:org_approver)
    article.text_for_state(article.current_state)
  else
    'test'
  end
end  

这篇关于Rails 4-如何在索引视图中使用辅助方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆