obj.update_attribute(:only_one_field, 'Some Value')
obj.update_attributes(field1: 'value', field2: 'value2', field3: 'value3')
Both of these will update an object without having to explicitly tell ActiveRecord to update.
Rails API says:
update_attribute
Updates a single attribute and saves the record without going through the normal validation procedure. This is especially useful for boolean flags on existing records. The regular update_attribute method in Base is replaced with this when the validations module is mixed in, which it is by default.
update_attributes
Updates all the attributes from the passed-in Hash and saves the record. If the object is invalid, the saving will fail and false will be returned.
So if I don't want to have the object validated I should use #update_attribute. What if I have this update on a #before_save, will it stackoverflow?
My question is does #update_attribute also bypass the before save or just the validation.
Also, what is the correct syntax to pass a hash to #update_attributes ... check out my example at the top.
Please refer to update_attribute. On clicking show source you will get following code
# File vendor/rails/activerecord/lib/active_record/base.rb, line 2614
2614: def update_attribute(name, value)
2615: send(name.to_s + '=', value)
2616: save(false)
2617: end
and now refer update_attributes and look at its code you get
# File vendor/rails/activerecord/lib/active_record/base.rb, line 2621
2621: def update_attributes(attributes)
2622: self.attributes = attributes
2623: save
2624: end
the difference between two is update_attribute uses save(false) whereas update_attributes uses save or you can say save(true).
Sorry for the long description but what I want to say is important. save(perform_validation = true), if perform_validation is false it bypasses (skips will be the proper word) all the validations associated with save.
For second question
Also, what is the correct syntax to pass a hash to update_attributes... check out my example at the top.
Your example is correct.
Object.update_attributes(:field1 => "value", :field2 => "value2", :field3 => "value3")
or
Object.update_attributes :field1 => "value", :field2 => "value2", :field3 => "value3"
or if you get all fields data & name in a hash say params[:user] here use just
Object.update_attributes(params[:user])
Tip: update_attribute is being deprecated in Rails 4 via Commit a7f4b0a1. It removes update_attribute in favor of update_column.
update_attribute
This method update single attribute of object without invoking model based validation.
obj = Model.find_by_id(params[:id])
obj.update_attribute :language, “java”
update_attributes
This method update multiple attribute of single object and also pass model based validation.
attributes = {:name => “BalaChandar”, :age => 23}
obj = Model.find_by_id(params[:id])
obj.update_attributes(attributes)
Hope this answer will clear out when to use what method of active record.
Also worth noting is that with update_attribute, the desired attribute to be updated doesn't need to be white listed with attr_accessible to update it as opposed to the mass assignment method update_attributes which will only update attr_accessible specified attributes.
update_attribute simply updates only one attribute of a model, but we can pass multiple attributes in update_attributes method.
Example:
user = User.last
#update_attribute
user.update_attribute(:status, "active")
It pass the validation
#update_attributes
user.update_attributes(first_name: 'update name', status: "active")
it doesn't update if validation fails.
You might be interested in visiting this blog post concerning all the possible ways to assign an attribute or update record (updated to Rails 4) update_attribute, update, update_column, update_columns etc. http://www.davidverhasselt.com/set-attributes-in-activerecord/. For example it differs in aspects such as running validations, touching object's updated_at or triggering callbacks.
As an answer to the OP's question update_attribute does not by pass callbacks.
Great answers.
notice that as for ruby 1.9 and above you could (and i think should) use the new hash syntax for update_attributes:
Model.update_attributes(column1: "data", column2: "data")
update_attribute and update_attributes are similar, but
with one big difference: update_attribute does not run validations.
Also:
update_attribute is used to update record with single attribute.
Model.update_attribute(:column_name, column_value1)
update_attributes is used to update record with multiple attributes.
Model.update_attributes(:column_name1 => column_value1, :column_name2 => column_value2, ...)
These two methods are really easy to confuse given their similar names and works. Therefore, update_attribute is being removed in favor of update_column.
Now, in Rails4 you can use Model.update_column(:column_name, column_value) at the place of Model.update_attribute(:column_name, column_value)
Click here to get more info about update_column.
To answer your question, update_attribute skips pre save "validations" but it still runs any other callbacks like after_save etc. So if you really want to "just update the column and skip any AR cruft" then you need to use (apparently)
Model.update_all(...) see https://stackoverflow.com/a/7243777/32453
Recently I ran into update_attribute vs. update_attributes and validation issue, so similar names, so different behavior, so confusing.
In order to pass hash to update_attribute and bypass validation you can do:
object = Object.new
object.attributes = {
field1: 'value',
field2: 'value2',
field3: 'value3'
}
object.save!(validate: false)
I think your question is if having an update_attribute in a before_save will lead to and endless loop (of update_attribute calls in before_save callbacks, originally triggered by an update_attribute call)
I'm pretty sure it does bypass the before_save callback since it doesn't actually save the record. You can also save a record without triggering validations by using
Model.save false
Related
I am new to rails and I try to find a validation method corresponding to validate the presence of an attribute when updating a record. If that attribute is not present, meaning the attribute does not exist from the request body, Rails should not update the record.
validates :description, presence: true
and
validates_presence_of :description
doesn't seem to do the job. Is there a method for this purpose? It seems quite common in every day scenarios.
If you say:
model.update(hash_that_has_no_description_key)
then you're not touching :description: sending a hash without a :description key to update is not the same as sending in a hash with :description => nil. If model is already valid (i.e. it has a description) then that update won't invalidate it because it won't touch :description.
You say this:
If that attribute is not present, meaning the attribute does not exist from the request body, Rails should not update the record.
Since you're talking about the request body (which models really shouldn't know anything about) then you should be dealing with this logic in the controller as it prepares the incoming data for the update call.
You could check in the controller and complain:
data = whatever_params
if(!data.has_key?(:description))
# Complain in an appropriate manner...
end
# Continue as now...
or you could include :description => nil if there is no :description:
def whatever_params
data = params.require(...).permit(...)
data[:description] = data[:description].presence # Or however you prefer to do this...
data
end
maybe you should use before_update..
see this: http://edgeguides.rubyonrails.org/active_record_callbacks.html#conditional-callbacks
but use before_update instead before_save..
I need to verify if the model could be saved with a specific params but without saving it
event_params = {:user => #current_user.id, :id => id, :value => value}
If I wanted to save it I could verify it easily with something like
x = e.update_attributes(event_params) if x.true? .... end
I have read that I could use assign_attributes that would basically do the same as update_attributes but without saving.
The problem is that with the assign_attributes it always returns nil, so I think I have no way to verify it the params would be valid or not on the model.
You can call the valid? method on any instance of a model object, to have it go through validations and verify if this can be persisted. Note that this doesn't guarantee persistence as you might have other constraints at the database level.
Reference: http://api.rubyonrails.org/classes/ActiveRecord/Validations.html#method-i-valid-3F
Is it possible to pass :symbols to the valid? method so that I can define if the object is valid up to a certain point?
Eg. if I have an object Person and want to call Person.valid?(:basic_info) and it will return true only if a certain subset of fields (say name & gender) are present?
I saw something that I thought might be of use but cannot get it working, it's conditional validations http://guides.rubyonrails.org/active_record_validations_callbacks.html#conditional-validation , in particular grouping conditional validations, but I couldn't get it working...
Can anyone help me out here please...
I don't think there already present like this however you can write a method on your own like following
def is_valid_field?(field)
self.valid?
self.errors[field].blank?
end
and then just person.is_valid_field?(:basic_info)
To validate basic_info you'll have to define a custom validator:
class Person < ActiveRecord::Base
validate :basic_info_present
def basic_info_present
if name.blank? || gender.blank?
errors.add(:basic_info, "can't be in blank")
end
end
end
If you then want to see if there are errors on the specific field, you can use #Salil's approach.
Note however that since there is no actual attribute called basic_info in your model, the validation errors here will not come up in forms, etc. (although they will be in the errors hash). That may or may not be what you want.
I got this to work using conditional validations, so now i can use .valid?(:basic) say for when i only want to check that the person has a name with the call...
validates_presence_of :name, :when => [:basic]
Documentation here: http://apidock.com/rails/ActiveRecord/Validations/valid%3F
This way I can have the object return true when calling .valid? even when it doesn't have a name, good times...
I'm trying to update single attribute of a user model from a admin controller (not users controller).
While doing this I tried update_attribute() but it was changing the users password also.
I think the password is changing because I have before_save method on user model which hashes the password.
update_attributes() is not working because it is checking the validations for password which is presence=>true
Is there any way to achieve this?
You can set a condition on your validations by using the :if option. In my code, it looks something like this:
validates :password,
:length => { :minimum => 8 },
:confirmation => true,
:presence => true,
:if => :password_required?
def password_required?
crypted_password.blank? || password.present?
end
So basically, it's only if the crypted_password in the database is not set (meaning a new record is being created) or if a new password is being provided that the validations are run.
Try update_column(name, value), it might work.
You can update single attribute of user like this
#user is that user whose attribute you want to update
e.g user_name
#user.update_attributes(:user_name => "federe")
Try it and it will only update one attribute..
ActiveRecord has an 'update-column' method that skips both validations and callbacks:
http://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-update_column
However, I'd suggest that could be dangerous - you have that :before_save filter for a reason. If you place an :except method on the filter to circumvent in specific cases, it not only becomes reusable but you keep behaviour consistent and avoid having a method buried in a controller that's bypassing your Model's validation/callback stack.
I'm personally not overly keen on seeing methods like update_column anywhere except as protected methods inside Models.
Try :
To bypass callback and validations use :
User.update_all({:field_name => value},{:id => 1})
Just wanted to let you know :
In Rails, update_attribute method bypasses model validations, while update_attributes and update_attributes! will fail (return false or raise an exception, respectively) if a record you are trying to save is not valid.
The difference between two is update_attribute use save(false) where as update_attributes uses save or you can say save(true) .
I'd like to create a callback function in rails that executes after a model is saved.
I have this model, Claim that has a attribute 'status' which changes depending on the state of the claim, possible values are pending, endorsed, approved, rejected
The database has 'state' with the default value of 'pending'.
I'd like to perform certain tasks after the model is created on the first time or updated from one state to another, depending on which state it changes from.
My idea is to have a function in the model:
after_save :check_state
def check_state
# if status changed from nil to pending (created)
do this
# if status changed from pending to approved
performthistask
end
My question is how do I check for the previous value before the change within the model?
You should look at ActiveModel::Dirty module:
You should be able to perform following actions on your Claim model:
claim.status_changed? # returns true if 'status' attribute has changed
claim.status_was # returns the previous value of 'status' attribute
claim.status_change # => ['old value', 'new value'] returns the old and
# new value for 'status' attribute
claim.name = 'Bob'
claim.changed # => ["name"]
claim.changes # => {"name" => ["Bill", "Bob"]}
Oh! the joys of Rails!
you can use this
self.changed
it return an array of all columns that changed in this record
you can also use
self.changes
which returns a hash of columns that changed and before and after results as arrays
For Rails 5.1+, you should use active record attribute method: saved_change_to_attribute?
saved_change_to_attribute?(attr_name, **options)`
Did this attribute change when we last saved? This method can be
invoked as saved_change_to_name? instead of
saved_change_to_attribute?("name"). Behaves similarly to
attribute_changed?. This method is useful in after callbacks to
determine if the call to save changed a certain attribute.
Options
from When passed, this method will return false unless the original
value is equal to the given option
to When passed, this method will return false unless the value was
changed to the given value
So your model will look like this, if you want to call some method based on the change in attribute value:
class Claim < ApplicationRecord
after_save :do_this, if: Proc.new { saved_change_to_status?(from: nil, to: 'pending') }
after_save :do_that, if: Proc.new { saved_change_to_status?(from: 'pending', to: 'approved') }
def do_this
..
..
end
def do_that
..
..
end
end
And if you don't want to check for value change in callback, you can do the following::
class Claim < ApplicationRecord
after_save: :do_this, if: saved_change_to_status?
def do_this
..
..
end
end
I recommend you have a look at one of the available state machine plugins:
acts_as_state_machine
alter_ego
Either one will let you setup states and transitions between states. Very useful and easy way of handling your requirements.
I've seen the question rise in many places, so I wrote a tiny rubygem for it, to make the code a little nicer (and avoid a million if/else statements everywhere): https://github.com/ronna-s/on_change.
I hope that helps.
You will be much better off using a well tested solution such as the state_machine gem.