AlexBrand
AlexBrand

Reputation: 12409

Fetching models that are similar - Rails

I have the following method inside my Business class:

def similar_businesses(n)
    Business.where(:category_id => category_id, :city_id => city_id).where("id NOT IN (?)",id).limit(n).order("RANDOM()")
end

It basically grabs n businesses that are in the same category and same city.

I was looking at a railscast that talks about using class methods instead of scopes, and tried to convert my code into:

def similar_businesses(n)
    where(:category_id => category_id, :city_id => city_id).where("id NOT IN (?)",id).limit(n).order("RANDOM()")
end

Notice Business is not there anymore.

However, I am getting an error undefined where method for ...

I have just started rails, and I am also wondering if there is any difference between these two methods? And why am I getting this error?

Upvotes: 1

Views: 37

Answers (2)

Jason Kim
Jason Kim

Reputation: 19041

It seems like you want to use similar_businesses as a class method rather than instance method. The difference between the two is that you play class method for classes, such as Business and you apply instance method for something like @business = Business.new.

Try using

def self.similar_businesses(n)
  where(:category_id => category_id, :city_id => city_id).where("id NOT IN (?)",id).limit(n).order("RANDOM()")
end

Upvotes: 1

Russell
Russell

Reputation: 12439

You need to define the method as def self.similar_businesses to make it a class method.

Upvotes: 1

Related Questions