简体   繁体   中英

How to modify a record before saving on Ruby on Rails

Looking for a way to either:

  • Change one of the fields of a new record (namely - force it to lower-case) before saving it to a RoR db. I've tried:

    before_create do |term| term.myfield.downcase! end

but this gives an error of:

undefined method `before_create' for RowsController:Class

or

  • Check that the field is all lowercase, and if not, raise an error message, and not create the record.

tried:

before_filter :check_lowcase, :only => [:new]
def check_lowcase
  if (Term.new =~ /[^a-z]+/)
    flash[:notice] = "Sorry, must use lowercase"
    redirect_to terms_path
  end
end

this seems to just be ignored....

You need to do it on your model, not your controller:

class YourModel < ActiveRecord::Base
 before_create :downcase_stuff

  private
    def downcase_stuff
      self.myfield.downcase!
     end
end

before_save { |classname| classname.myfield = myfield.downcase }

    before_create :lower_case_fields

    def lower_case_fields
       self.myfield.downcase!
    end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM