How can this be re-written as an ActiveRecord query? (Rails)

I have the following method in a controller:

# GET /units/1
def show
    @unit = Unit.find(params[:id]

    @product_instances = Array.new
    current_user.product_instances.each do |product_instance|
        if product_instance.product.unit == @unit
            @product_instances.push(product_instance)
        end
    end

    ... #rest of method
end

As can be seen, I have four tables/models: User, Product, ProductInstance, and Unit. A User has many ProductInstances. Each ProductInstance maps to a Product. A Unit has many Products.

I would like to fetch only the User's ProductInstances that are linked to a Product in the current Unit. The current code does it, but how can I re-write it better? I'd like to get rid of the for-each loop and if statement and replace it with chained ActiveRecord queries, if possible.

I tried something like below but it didn't work:

@product_instances = current_user.product_instances.where(:product.unit => @unit)

Seems you cannot do :product.unit.

Upvotes: 1

Views: 64

Answers (1)

Aditya Sanghi
Aditya Sanghi

Reputation: 13433

I think you can try this

current_user.product_instances.joins(:product).where("products.unit_id = ?",@unit.id)

or with hashes

current_user.product_instances.joins(:product).where(:products => {:unit_id => @unit.id})

Upvotes: 1

Related Questions