【问题标题】:helper method to check if a record is owned by the current user in rails辅助方法来检查记录是否由 Rails 中的当前用户拥有
【发布时间】:2013-06-21 01:38:16
【问题描述】:

我正在构建一个 rails 3 应用程序,我正在使用设计来管理身份验证逻辑,但我想知道是否有一个辅助方法来检查当前用户是否拥有一个对象(数据库中的记录),该对象具有关联“has_many”。

示例:

User

has_many :reports 

我有这种情况:

<%=  current_user.id == report.user.id ? "Personal Report" : report.user.username %>

可以创建类似的东西:

<%= owned ? "yes" : "no" %>

谢谢

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 authentication view-helpers


    【解决方案1】:

    助手:

    def owned(report)
        current_user.id == report.user_id
    end
    

    用法:

    <%= owned(report) ? "yes" : "no" %>
    

    【讨论】:

    • 它不能工作,因为助手不知道视图之外的报表模型的关联方法,我不会像参数一样传递report.user.user_id。每次我使用拥有的助手
    • @davelab Helper 方法被视为在视图中声明。所以他们可以访问传递的对象。
    • @davelab 如果您有权访问视图中的报告,则可以使用此辅助方法
    【解决方案2】:

    您可以在 Report 模型中定义此方法:

    型号受限:

    class Report < ActiveRecord::Base
    
      def owned_by?(user)
        self.user_id == (user.try(:id) || user)
      end
    

    然后像这样使用它:

    <%= report.owned_by?(current_user) ? 'yes' : 'no' %>
    

    这个owned_by?(user) 方法接受一个用户对象和一个整数(user_id)。

    与用户关联的每个模型的通用方法:

    辅助方法可以解决问题:

    module OwnerHelper
      def is_owner?(object)
        return nil if(current_user.nil? || !object.respond_to(:user_id))
        current_user.try(:id) == object.try(:user_id)
      end
    end
    

    如果current_user 是所有者,此帮助程序将返回true,如果不是,则返回false,如果current_usernil 或对象没有user_id 属性,则返回nil

    【讨论】:

    • 小错字:您在方法定义和解释中使用了owner_by。尝试自己修复它,但编辑必须更改至少 6 个字符。
    • 谢谢@ChrisFletcher,我修好了!
    • 我想为每个与用户关联的模型提供一个通用方法。
    • @MrYoshiji 通用方法做得很好,真的很好! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-03
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-07
    相关资源
    最近更新 更多