【问题标题】:Rails 4 - how to use a helper method in an index viewRails 4 - 如何在索引视图中使用辅助方法
【发布时间】:2016-11-25 19:51:30
【问题描述】:

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

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

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

即:
在我的文章助手中有一个助手方法为:

 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”方法在我的文章政策中定义(我使用权威人士)。

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

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

.

谁能看出我哪里出错了?

【问题讨论】:

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


    【解决方案1】:

    尝试关注。

    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  
    

    【讨论】:

      【解决方案2】:

      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
      

      【讨论】:

      • 嗨,山姆。我试过了,但我得到了相同的结果(没有错误,只是文本应该是一个空白字段)。我想也许在索引视图中传递(文章)就足以确定我想使用帮助器的文章。
      • 您文章的 current_state 可以为空吗?如果将 替换为 会发生什么?还是空白?
      • 嗨,Sam - 它显示了我进行更改时的当前状态。状态不能为空,因为状态是用新文章初始化的(状态=草稿)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-22
      • 1970-01-01
      • 2015-09-03
      • 1970-01-01
      • 1970-01-01
      • 2012-06-28
      相关资源
      最近更新 更多