Rails 4 - 如何在索引视图中使用辅助方法

时间:2016-07-22 03:01:04

标签: ruby-on-rails ruby-on-rails-4 helper

我在索引视图中试图使用辅助方法时遇到困难。

在我的索引中,我有这样的观点:

<% 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" %>

以下行:&lt;%= text_for_state(article)%&gt;
在我的文章助手中有一个帮助方法:

 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

方法&#39; to_be_reviewed&#39;在我的文章政策中定义(我使用权威)。

我希望索引视图能够评估用户是否应该获取帮助程序中列出的3种情况之一的文本。相反,我收到一条错误消息:

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

谁能看到我出错的地方?

2 个答案:

答案 0 :(得分:0)

article来自哪里?不应该是你的帮助者:

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

答案 1 :(得分:0)

尝试以下。

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