问题
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