我为虚拟属性stock
对于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
答案 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
您可能需要稍微调整一下才能使其完美运行。