我怎么能干掉不同模型

时间:2016-06-05 08:21:05

标签: ruby-on-rails

我为虚拟属性stock

编写了setter和getter

对于getter,它将聚合HAM_MANY关系记录。 对于setter,它将创建一个新记录并将记录保存到正确的子表。

我怎么能干这两种模式中的两种方法?

我怎样才能避免在不同的模型文件中有两个相同的代码?感谢

模型飞行

  has_many :stocks, foreign_key: "flight_sku_fare_id", class_name: "FlightSkuFareStock", dependent: :destroy

  def stock
      stocks.sum(:amount)
  end

  def stock=(stock_value)
      self.save
      stock_delta = stock_value - self.stock
      if stock_value >=0 and (stock_delta!=0)
          self.stocks.create(amount: stock_delta)
      end
  end

样板房

  has_many :stocks, foreign_key: "room_sku_id", class_name: "RoomSkuStock", dependent: :destroy


  def stock
    stocks.sum(:amount)
  end

  def stock=(stock_value)
      self.save
      stock_delta = stock_value - self.stock
      if stock_value >=0 and (stock_delta!=0)
          self.stocks.create(amount: stock_delta)
      end
  end

1 个答案:

答案 0 :(得分:1)

您可以查看active_support/concern

应用/模型/关切/ stock_concern.rb

require 'active_support/concern'

module StockConcern
  extend ActiveSupport::Concern

  def stock
    stocks.sum(:amount)
  end

  def stock=(stock_value)
    self.save
    stock_delta = stock_value - self.stock
    if stock_value >=0 and (stock_delta!=0)
        self.stocks.create(amount: stock_delta)
    end
  end
end

在你的模特中,

应用/模型/ flights.rb

class Flight < ActiveRecord::Base
  include StockConcern

  ## other methods
end

应用/模型/ rooms.rb

class Room < ActiveRecord::Base
  include StockConcern

  ## other methods
end

您可能需要稍微调整一下才能使其完美运行。