I want to implement a conditional update method on a specific set of values for a key.
I want to allow updates only if the original list.permissions values (set on create) equal either "public", "viewable, or "editable". If the list.permissions value for a record does not equal one of those three acceptable values, updating the record is denied (locked).
I tried modifying the strong params in a private method in the controller file:
def list_params_validated
params.require(:list).permit(:title, permissions: ["public", "viewable", "editable"])
end
and then calling that in my update
method in the same controller:
def update
list = List.find(params[:id])
if list.update(list_params_validated)
render json: list
else
render json: { errors: list.errors.full_messages }, status: :unprocessable_entity
end
end
no luck with this, any help would be most appreciated!
You can add an custom validation on your List
model as following and call simple update
in controller.
self.permissions
value should be string
like "public"
or "viewable"
or "editable"
.
validate :validate_editable, :validate_permissions:on => :update
def editable?
self.permissions != "locked"
end
private
def validate_editable
errors.add(:base, "Not Ediable!") unless editable?
end
def validate_permissions
unless ["public", "viewable", "editable"].include?(self.permissions)
errors.add(:base, "Permission denied!")
end
end