Gugubaight Gugubaight - 2 months ago 17
Ruby Question

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.

max max
Answer

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