ruby - Rails 4.2: has_many using condition from belongs_to -
i have 3 activerecords. order, has_many orderitems. has field named status. orderitem, belongs_to order , script script, has_many orderitems
i want set has_many in script model orderitems belong order has status of 'paid' given.
i'm new rails, , isn't codebase i'm struggling bit. i've seen other answers use :include , :conditions keywords, neither valid in rails 4.2
any great.
i try keeping things bit pure ensuring models not involved in defining how other models behave.
start defining scope order define mean "paid".
def self.has_been_paid where(status: "paid") end
then can associate orderitems paid order.
belongs_to :paid_order, -> {merge(order.has_been_paid)}, :class_name => "order", :foreign_key => :order_id
... , scope ...
def self.for_paid_orders joins(:paid_order) end
then script:
has_many :order_items, -> {merge(orderitem.for_paid_orders)}
so each model takes care of own business.
Comments
Post a Comment