Gugubaight Gugubaight - 1 year ago 96
Ruby Question

Rails 4: Model Logic - (Limited Associations)

Is there a way to use a similar command to

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

Tool Index View:

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

I expect something like:
@boughttools = current_user.purchases.where(status: "Completed", user_id:
The only difference is that I need
instead of
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
table and not on the

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

max max
Answer Source

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


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download