Search code examples
ruby-on-railsrubyruby-on-rails-4activerecordhas-many

Rails 4.2: has_many using condition from belongs_to


I have three ActiveRecords. Order, which has_many OrderItems. Also has a field named status. OrderItem, which belongs_to an Order and a Script Script, which has_many OrderItems

I want to set up the has_many in the Script model so that only OrderItems that belong to an Order which has a status of 'paid' are given.

I'm new to rails, and this isn't my codebase so I'm struggling a bit. I've seen other answers use the :include and :conditions keywords, but neither are valid in rails 4.2

Any help would be great.


Solution

  • I would try keeping things a bit pure by ensuring that the models do not get too involved in defining how other models behave.

    Start by defining a scope for Order to define what you mean by "paid".

    def self.has_been_paid
      where(status: "Paid")
    end
    

    Then you can associate OrderItems with a paid Order.

    belongs_to :paid_order, -> {merge(Order.has_been_paid)}, :class_name => "Order", :foreign_key => :order_id
    

    ... and a scope ...

    def self.for_paid_orders
      joins(:paid_order)
    end
    

    Then for the Script:

    has_many :order_items, -> {merge(OrderItem.for_paid_orders)}
    

    So now each model takes care of its own business.