Jump to content

The ultimate community for Ruby on Rails developers.


Photo

Rails 4.+ and before_save method

before_save Rails 4

  • Please log in to reply
3 replies to this topic

#1 Alain ANDRE

Alain ANDRE

    Passenger

  • Members
  • 6 posts
  • LocationBordeaux

Posted 06 April 2014 - 12:25 PM

Hi all, I'm using the doc at http://apidock.com/ to help me learn RoR and I'm afraid about a usefull callback that seems not to exsist anymore : before_save

 

The doc says : This method is deprecated or moved on the latest stable version. The last existing version (v2.3.8) is shown here.

But it does not say what's the new method to use and I cannot find info on the net.

 

I'm trying to use before_save in a product class :

class Product < ActiveRecord::Base
  validates_presence_of :title, :description, :image
  validates_numericality_of :price
  validates_uniqueness_of :title
  before_save :validate

  def self.find_products_for_sale
    find(:all, :order => "title")
  end

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

Can someone tell me what is the method to use with rails 4+ ?



#2 Jemagee

Jemagee

    Inspector

  • Members
  • 62 posts

Posted 06 April 2014 - 05:23 PM   Best Answer

I have had no issues using validation and before_save - but why write a special function when there is already a built in validation for :greater_than_or_equal_to

 

The full description of numericality validations can be found in the rails guide at rubyonrails.org



#3 Alain ANDRE

Alain ANDRE

    Passenger

  • Members
  • 6 posts
  • LocationBordeaux

Posted 06 April 2014 - 07:17 PM

Great, thanks for the info.

 

I created this because I had no idea validates_numericality_of had this method.

validates_numericality_of :price, :greater_than_or_equal_to => 0.01

I will have more look at http://guides.rubyonrails.org.



#4 Jemagee

Jemagee

    Inspector

  • Members
  • 62 posts

Posted 06 April 2014 - 07:20 PM

Neither did I ;)  I looked it up - you can get copies of the rails guides on your computer (rake doc:guides) if you have the right gems installed (redcloth, nokogiri, and one other I forget off the top of my head)...glad there's some beginners out there like me :)







Also tagged with one or more of these keywords: before_save, Rails 4

1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users