【问题标题】:How to have a model field inherit from another model?如何让模型字段从另一个模型继承?
【发布时间】:2014-06-26 19:13:21
【问题描述】:

我正在使用 money-rails gem 来处理货币。我有两个模型:用户模型和目标模型。 User 模型有一个:currency 字段,money-rails 使用该字段为用户设置货币。目标模型还有一个:currency 字段。就目前而言,当用户创建一个新目标时,控制器会将该目标的货币设置为与存储在用户模型中的值相同的值。

如下:

if @goal.save
  @goal.update_attribute(:currency, current_user.currency)
  redirect_to goals_path, notice: "Goal created!"
else
  render '/goals/new'
end

但是,如果用户随后返回并通过编辑 User 模型更改其货币,这只会更改随后创建的目标的货币。如何设置它以便当用户更改其货币时,它会更改所有模型中使用的货币?

提前谢谢你!

【问题讨论】:

    标签: ruby-on-rails ruby model money-rails


    【解决方案1】:

    一种方法是在 User 模型中使用 after_save 回调将更改级联到所有用户的目标:

    class User < ActiveRecord::Base
      has_many :goals
    
      after_save :cascade_currency_changes
    
      def cascade_currency_changes
        if currency_changed?
          goals.update_all currency: currency
        end
      end
    end
    

    【讨论】:

      【解决方案2】:

      另一种方法是从目标模型中删除该字段并拥有一个自定义字段:

      class Goal < ActiveRecord::Base
          belongs_to :user
          #....
      
          def currency
               user.currency
          end
      end
      

      因此,无需任何计算,始终:

      @goal.currency == @goal.user.currency # => always true
      

      【讨论】:

        猜你喜欢
        • 2012-08-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-21
        • 2021-06-18
        • 1970-01-01
        相关资源
        最近更新 更多