如何在轨道模型中自动包含一些位置条件?



我有几个模型具有office_idfiscal_year_id属性。我希望这些字段在查询之前自动设置。因此,我不必担心数据从一个办公室重叠到另一个办公室,从一个财政年度重叠到另一个财政年度。

ActiveSuppport::CurrentAttributes 提供了你需要的东西。

请参阅此处的文档。

app/models/concern/fiscalable.rb

module Fiscalable
extend ActiveSupport::Concern
def office_id
super || 1 # default office_id
end
def fiscal_year_id
super || Time.zone.now.year
end
end

在您的模型中。

class Model < ActiveRecord
include Fiscalable 
...
end

在视图中。

<%= @object.fiscal_year_id %>

最新更新