how to update attributes in self model rails

谁都会走 提交于 2019-12-07 17:21:27

问题


how to update self model in rails?

class BillSubTotal < ActiveRecord::Base
  def self.total
    self.update_attributes(:total => 150)
  end
end

i want update value in model BillSubTotal from self model?


回答1:


Depends on what you're wanting to do as how you'd go about this.

Rails automatically creates the getter/setter methods for database columns, so you don't have to create that functionality explicitly, and can just set the method like so:

class BillSubTotal < ActiveRecord::Base
  def update_total
    self.total = 150
  end
end

Or if you're working with an instance of the class directly:

bill_subtotal_instance.total = 150



回答2:


This is another convenient way to update attribute through model. You have to call a method after create and with in that method you can update your required attribute. Here is the code snippet.

class MyModel < ActiveRecord::Base

    after_create :insert_default_data

    def insert_default_data
       self.update_attributes!(column_name: value)
    end
 end

Here, insert_default_data method will call after saving a new record in the database. I think it will helpful for you...



来源:https://stackoverflow.com/questions/19217097/how-to-update-attributes-in-self-model-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!