简体   繁体   中英

Ruby on Rails: How do I execute a function before saving to the database?

I want to alter the data and save it then to the database when using the new / create function of the app.

before_create :myfunction

def myfunction
  # Edit data
end

Should do the trick.

You should use active callbacks, as the two other answers stated. The *before_create* is definitely the one you are looking for. Always do that kind of logic in the model, and not in the controller. Rails mantra (one of many) is "thin controller, fat model", which enable code reuse more easily.

You can check the active callbacks documentation at:

http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

Also, here is an example of what you want to achieve

class MyClass < ActiveRecord::Base
    before_create :alter_my_data

    def alter_my_data
        # any manipulation you want to do here before saving
    end
end
class User < ActiveRecord::Base
  before_create :validate_username

  def validate_username
    raise "blank error" if username.blank?
    #....your code
  end
end

Your question has already been answered above, but I really recommend you check out the official Ruby on Rails guides:

http://guides.rubyonrails.org/

The guides are easy to comprehend and cover many parts of Rails. Your question is answered in the 'Active Record Validations and Callbacks' section.

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