Gugubaight
Gugubaight

Reputation: 187

Rails 4: Model Logic - (Limited Associations)

Is there a way to use a similar command to .where() in the Model?

In my instance I want to loop through items but I want to check for a database value first:

User Model:

has_many :purchases
has_many :purchasedtools, through: :purchases, source: :tool #only where "status: "Completed"!

Purchase Model:

belongs_to :user
belongs_to :tool

Tool Model:

belongs_to :user
has_many :purchases

Tools Controller:

def index
    @boughttools = current_user.purchasedtools
end

Tool Index View:

- @boughttools.limit(4).each do |tool|

I expect something like: @boughttools = current_user.purchases.where(status: "Completed", user_id: current_user.id).
The only difference is that I need purchasedtools instead of purchases because I want the actual Tools as source.

Fortunately I can't just change this as is because the db values I check are on the purchase table and not on the tool table.


Thanks in advance for each answer! Please tell me if you need additional information.

Upvotes: 0

Views: 32

Answers (3)

max
max

Reputation: 102423

To add a scope to an association you simply pass a lambda or proc to the association macro:

class User
  has_many :purchases
  has_many :completed_purchases, ->{ where(status: 'Complete') },
    class_name: 'Purchase'
  has_many :purchased_tools
    through: :completed_purchases
    source: :tool
end

Added

A simpler way to do this as noticed by the OP would just be to specify that the condition applies to the join table:

  has_many :purchased_tools, -> { where(purchases: {status: "Completed"} ) }
    through: :completed_purchases
    source: :tool

See Scopes for has_many

Upvotes: 2

Andrey Deineko
Andrey Deineko

Reputation: 52377

As I suggested in my comment, you might be looking for a conditional association:

has_many :purchasedtools,
         -> { where(status: 'Completed') }
         through:    :purchases,
         source:     :tool

Check out docs for more info on associations.

Upvotes: 3

Bartłomiej Gładys
Bartłomiej Gładys

Reputation: 4615

You can use joins

Purchase.joins(:tool).where(tools: {user_id: current_user.id}, purchases: {status: 'Completed'})

Upvotes: 0

Related Questions