05 Nov 2013, 06:05
Me_pragsmall

Colin Williams (9 posts)

Hi, I copied the Product class below. I see the validates (is it a keyword or a method ? ) below checks title, description, image_url,price, etc.

Are title, description, image_url, price considered instance fields of the Product class or something else?

Also it seems that validates generates these “fields” into the corresponding database? Ae they generated by the rails generate command which was run in the terminal?

`

class Product < ActiveRecord::Base has_many :line_items

before_destroy :ensure_not_referenced_by_any_line_item

def self.latest Product.order(:updated_at).last end validates :title, :description, :image_url, presence: true validates :price, numericality: {greater_than_or_equal_to: 0.01} validates :title, uniqueness: true validates :image_url, allow_blank: true, format: { with: %r{.(gif|jpg|png|jpeg)\Z}i, message: ‘must be a URL for GIF, JPG, or PNG image.’ } private

 # ensure that there are no line items referencing this product
 def ensure_not_referenced_by_any_line_item
   if line_items.empty?
     return true
   else
     errors.add(:base,'Line Items present')
     return
 end    end    end `
05 Nov 2013, 15:23
Samr_small_pragsmall

Sam Ruby (584 posts)

I see the validates (is it a keyword or a method ? )

validates is a class method.

Are title, description, image_url, price considered instance fields of the Product class or something else?

Yes, though Ruby calls such attributes.

Also it seems that validates generates these “fields” into the corresponding database?

No, validates generates code which tests the values of the attributes.

Ae they generated by the rails generate command which was run in the terminal?

Indirectly, yes. The generate command produces a migration. The migration updates the schema of the database. ActiveRecord uses the schema of the database to generate the attributes.

05 Nov 2013, 18:33
Me_pragsmall

Colin Williams (9 posts)

I guess what was shocking to me is that the attributes are not necessarily defined in the Class file itself. I see now that I can consult the /db/schema.rb file, or use the rails console to find what attributes a Class has.

Furthermore I see that the attibutes seem to be a subset of the instance variables . Thanks for your input Sam, I feel like I’m starting to understand a little more.

  You must be logged in to comment