Why is this method protected? (from agile book)


#1

Hello,

This is form the 2.ed agile book in the product model:

/models/product.rb:

validates_presence_of :title, :description, :image_url
validates_numericality_of :price
validates_uniqueness_of :title

protected
def validate
errors.add(:price, “should be at least 0.01”) if price.nil? || price <
0.01
end

Why does the method that checks the price have to be protected?

Couldnt I, instead of the method just write:

validates_numericality_of :price, :minimum => 0.01

Thanks in advance.


#2

Hi, this would work because for the simply fact that :minimum isn’t a
configuration option for validates_numericality_of. At this time, the
config options are as follows:

Configuration options:

message - A custom error message (default is: “is not a number”)

on - Specifies when this validation is active (default is :save, other
options :create, :update)

only_integer - Specifies whether the value has to be an integer, e.g.
an integral value (default is false)

allow_nil - Skip validation if attribute is nil (default is false).
Notice that for fixnum and float columsn empty strings are converted
to nil

Good luck,

-Conrad


#3

I think the response is twofold. As for AWDRv2, I think the point of
the chapter is to demonstrate the different ways that validation can
be added to a model. The first dozen or so chapters are dedicated to
a somewhat real world example. Take them for what they are, realizing
that you might want to do things differently.

As for your specific question, “validate” is a protected method of
ActiveRecord::Base. If you want to extend it (the point of the AWDR
example) then you’ve got to implement the full signature of the
method, including it’s ‘protectedness’.

HTH,
AndyV

On Mar 18, 6:53 pm, Al Cholic removed_email_address@domain.invalid


#4

On Mar 23, 2007, at 6:29 PM, Al Cholic wrote:

Yes, I understand that the method is prected and the variables
inside it
can only be used inside the method itself. But, why does it need
to be
protected?

Because it never should be called from outside the context of the model.

Regards

Dave T.


#5

AndyV wrote:

I think the response is twofold. As for AWDRv2, I think the point of
the chapter is to demonstrate the different ways that validation can
be added to a model. The first dozen or so chapters are dedicated to
a somewhat real world example. Take them for what they are, realizing
that you might want to do things differently.

As for your specific question, “validate” is a protected method of
ActiveRecord::Base. If you want to extend it (the point of the AWDR
example) then you’ve got to implement the full signature of the
method, including it’s ‘protectedness’.

HTH,
AndyV

On Mar 18, 6:53 pm, Al Cholic removed_email_address@domain.invalid

Yes, I understand that the method is prected and the variables inside it
can only be used inside the method itself. But, why does it need to be
protected?