Reputation: 7409
I wrote setter and getter for the virtual attribute stock
For the getter it will aggregate the HAM_MANY relation records. For the setter, it will create a new record and save the record to the right child table.
How could I DRY the two methods in the two models?
How could I avoid have two identical code in different model files? Thanks
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
Upvotes: 1
Views: 71
Reputation: 1745
You can look into active_support/concern.
app/models/concerns/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
And in your models,
app/models/flights.rb
class Flight < ActiveRecord::Base
include StockConcern
## other methods
end
app/models/rooms.rb
class Room < ActiveRecord::Base
include StockConcern
## other methods
end
You might have to tweak it a little bit to make it work perfectly.
Upvotes: 1