dimitry_n
dimitry_n

Reputation: 3019

Method to return a collection - Ruby

Say, I have a method called posted_listings, which is supposed to run an ActiveRecord query and return a collection of User.listings where posted: true, with posted? being a Listing class method. So far I have been doing:

class Bar < ActiveRecord::Base
  def posted_listings
    posted_listings = []
    listings.each { |listing| posted_listings << listing if listing.posted? }
    posted_listing
  end
end

but each time this query runs I start feeling really bad about my skills (or lack of thereof). What is the most efficient way to return a collection of posted listings?

Edit:

posted? is not an attribute, its a class method:

class Listing < ActiveRecord::Base
 def posted?
    true if quantity >= 1 && has_sellers? 
  end
end 

def has_sellers?
  sellers.count >=1 #association to Seller
end

Upvotes: 0

Views: 292

Answers (2)

dhouty
dhouty

Reputation: 1989

I would recommend adding a scope to your Listing model like this:

scope :posted, -> { where(posted: true) }

Then you can get all posted listings like this:

@user.listings.posted

You can learn more about scopes here if you are interested.

UPDATE

Try this scope instead:

def self.posted
  joins(:sellers)
    .where('posted = ? AND quantity > ?', true, 0)
    .group('listings.id')
    .having('COUNT(sellers.id) > ?', 0)
end

Upvotes: 3

thaleshcv
thaleshcv

Reputation: 752

Your question is not so clear for me.

You may try:

User.listings.where(posted: true)

to get all users' posted Listings.

Or, saying @useris an User instance:

@user.listings.where(posted: true)

to get posted Listings from an specific user.

Upvotes: 0

Related Questions