开发者

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

开发者 https://www.devze.com 2023-03-18 19:48 出处:网络
I want to alter the data and save it then to the database when using the new / create fu开发者_运维百科nction of the app. before_create :myfunction

I want to alter the data and save it then to the database when using the new / create fu开发者_运维百科nction 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消