简体   繁体   中英

Extend model.save method Rails

Can I take the.save method of certain activeRecord models and add functionality to it? I would also like to use some of the attributes of the item being saved in that function

Can I do something like?

class Item < ActiveRecord::Base
    def self.save
        <added stuff for save>
        <including some_other_id_from_this_item>
    end
end

or will that break things? And how do I actually access this_item.the_column_i_need?

You should use ActiveRecords callbacks to extend the behavior of save.

With the before_save hook you can access data before the record is saved, for example to change case of entered email you can do something like

class User < ActiveRecord::Base
  before_save :downcase_email

  def downcase_email
    email.downcase!
  end
end

use callback aftet_save instead. access to any column just by attribute name if you read and self.db_column_name if you need to change it

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