Joshua Leung
Joshua Leung

Reputation: 2399

How to validate the presence of attributes when updating a record?

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.

Upvotes: 0

Views: 267

Answers (2)

mu is too short
mu is too short

Reputation: 434595

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

Upvotes: 2

Ricardo CF
Ricardo CF

Reputation: 79

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..

Upvotes: 1

Related Questions