ruby on rails - How to validate the presence of attributes when updating a record? -
i new rails , try find validation method corresponding validate presence of attribute when updating record. if attribute not present, meaning attribute not exist request body, rails should not update record.
validates :description, presence: true
and
validates_presence_of :description
doesn't seem job. there method purpose? seems quite common in every day scenarios.
if say:
model.update(hash_that_has_no_description_key)
then you're not touching :description
: sending hash without :description
key update
not same sending in hash :description => nil
. if model
valid (i.e. has description) update
won't invalidate because won't touch :description
.
you this:
if attribute not present, meaning attribute not exist request body, rails should not update record.
since you're talking request body (which models shouldn't know about) should dealing logic in controller prepares incoming data update
call.
you check in controller , complain:
data = whatever_params if(!data.has_key?(:description)) # complain in appropriate manner... end # continue now...
or include :description => nil
if there no :description
:
def whatever_params data = params.require(...).permit(...) data[:description] = data[:description].presence # or prefer this... data end
Comments
Post a Comment