Active Record清除模型after_find回调的实例

时间:2013-08-14 11:11:46

标签: ruby-on-rails activerecord rails-activerecord

我已经定义了一个回调after_find,用于根据检索到的模型实例检查一些设置。如果未满足设置,我不希望从find方法返回实例。那可能吗?

一个例子 控制器看起来像:

class UtilsController < ApplicationController
  def show
    @util = Util.find(params[:id])
  end 
end

模特:

class Util < ActiveRecord::Base
  after_find :valid_util_setting

  def valid_util_setting
    # calculate_availability? complex calculation 
    # that can not be part of the sql statement or a scope 

    unless self.setting.calculate_availability?(User.current.session)
      #if not available => clear the record for view
    else
      #nothing to do here
    end 
  end 
end

3 个答案:

答案 0 :(得分:1)

您可以只提出异常,而不是尝试清除记录吗?

E.g。

unless self.setting.calculate_availability?(User.current.session)
  raise ActiveRecord::RecordNotFound
else
...

答案 1 :(得分:0)

我担心你无法清除此次回调中的记录 也许你应该从一开始就找到所有选择的范围? 即@util = Util.scoped.find(params[:id])

答案 2 :(得分:0)

我找到了解决方案

def valid_util_setting
  Object.const_get(self.class.name).new().attributes.symbolize_keys!.each do |k,v| 
    begin
      self.assign_attributes({k => v})#, :without_protection => true)
    rescue ActiveModel::MassAssignmentSecurity::Error => e; end
  end
end

有了这个,我就可以创建一个几乎空的对象

相关问题