【问题标题】:Can't use methods in the application helper for cancan ability.rb无法使用应用程序助手中的方法来获取 cancan 能力.rb
【发布时间】:2014-11-11 16:56:22
【问题描述】:

我正在使用 Devise 和 cancancan。在我的应用程序助手中,我有 -

def is_part_of_team?(book)
    on_team = false
    book.contributions.each do |contribution|
        if contribution.user == current_user
            on_team = true
        end
    end
    if book.user == current_user
        on_team = true
    end
    return on_team
end

在ability.rb中我有 -

include ApplicationHelper
...
can :update, Book do |book|
  is_part_of_team?(book)
end

...这会引发错误 -

undefined local variable or method `current_user' for #<Ability...

可能有更好的方法可以做到这一点,但我只是想知道为什么 cancan 不喜欢应用程序助手中的 current_user。为什么是这样?我从视图中使用此功能,这一切都很花哨。

【问题讨论】:

    标签: ruby-on-rails devise cancan


    【解决方案1】:

    我的方法很糟糕。

    我不明白我可以使用这个而不是帮助程序中的所有代码 -

    book.contributions.where(user_id: user.id).any?
    

    ...得到完全相同的结果。这意味着在ability.rb 中我可以拥有这个 -

      can :update, Book do |book|
        (book.try(:user) == user) || book.contributions.where(user_id: user.id).any?
      end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-17
      相关资源
      最近更新 更多