user2514224
user2514224

Reputation: 197

Rails uppercase/lowercase object

This is a fairly basic Ruby/Rails question but I'm not sure why it makes a difference if you call a class of an object in some circumstances vs calling an instance of that object in different places of the framework.

Say you have a model e.g. Product and you call Product.new you have a new instance of the class. But if you have certain methods that are defined in the model I only seem to be able to access these if I call the Class rather than an instance e.g. Product.where(param, param). But I cannot call product.where(param, param) - why is this?

Upvotes: 0

Views: 525

Answers (2)

Mohamad
Mohamad

Reputation: 35349

There are two types of methods: Class methods, and instance methods. You must call the appropriate method on the right object.

class Product
  def self.foo
    # class method, only callable on Product
  end

  def name
    # instance method, callable on an instance of Product.
  end
end

If you attempt to call an instance method on a class, or vice versa, you'll see an undefined method error.

To use someone else's analogy, imagine a house and a blue print; the class is a blue print for an object, while a house would represent the instance. An instance of that class will have its own set of attributes (wall colour, window type, etc...).

Upvotes: 1

Nick Veys
Nick Veys

Reputation: 23939

What would this mean?

p = Product.find(1)
p.where('something == 2')

That doesn't make any sense, you have an instance, what are you querying for? Good API design results in methods defined where they make sense.

Upvotes: 0

Related Questions