代码之家  ›  专栏  ›  技术社区  ›  Kyle West

如何为特定模型的所有ActiveRecords查询添加条件?

  •  1
  • Kyle West  · 技术社区  · 16 年前

    我正在使用sentent\u user gem访问应用程序中的当前\u user对象。我想覆盖默认的ActiveRecordBase查询,将它们限定到当前用户。

    例如,我不希望我的用户查看、删除、修改其他用户的订单。

    提前谢谢。

    2 回复  |  直到 16 年前
        1
  •  4
  •   PreciousBodilyFluids    16 年前

    在控制器中,使用如下查询:

    @orders = current_user.orders.find(params[:id])
    

    http://ryandaigle.com/articles/2008/11/18/what-s-new-in-edge-rails-default-scoping

    例如:

    class Order < ActiveRecord::Base
      default_scope :order => 'created_at DESC', :conditions => { :processed => true }
    end
    

    然后,所有订单查询都将按降序创建,并且只返回processed=true的记录,除非您特别重写其中任何一个选项。

        2
  •  1
  •   Franck Verrot    16 年前

    默认作用域的主要问题是,当链接多个作用域时,它不会被更多地使用,因此不能在模型中使用“作用域到当前用户”的逻辑。

    我相信AR关联的真正用法(has\ u many:orders)应该只检索与在应用程序中执行操作的用户相关的命令。

    如果您现在想保护您的对象,您可以使用授权系统(如ACL9)或实现您自己的授权系统,例如,在您的情况下,将模型放入:

    # Order model
    class Order < AR::Base
      belongs_to :customer
    
      def is_allowed_to(action, performer)
        case action
          when 'show'
            performer.id == self.customer.id
          when 'update'
            performer.id == self.customer.id
          when 'destroy'
            performer.is_a? Administrator
          ....
      end
    end
    

    before filter is_allowed_to 检查权限。 action 参数将是实际操作名称或您选择的另一个名称。

    我希望这会有帮助。

    推荐文章