How to โ€œblockโ€ a record from updating or deleting?

I have a User model that automatically generates Task .

I want to block this task from editing or deleting.

What modifications of my controller do I need to do? Is there an elegant solution, or do I need to check every time you edit / delete if this is the task in question.

+4
source share
2 answers

As I know, there is no elegant solution, you will need to check every time in the controller, but it is simple by specifying this method in your controller:

 def find_task @task = Task.find(params[:id]) if @task.locked? flash[:error] = "This task is locked and cannot be altered at this stage." redirect_to tasks_path and return end end 

You can then call this method as before_filter for the actions that concern you. before_filter nil (which makes return ), before_filter will stop and the action will not be executed.

+2
source

You can use validation to do this pretty well.

 class Thing < ActiveRecord::Base validate :locked_cannot_be_modified private def locked_cannot_be_modified errors.add(:base, "Entry is locked") if changes.any? && whatever_logic_makes_it_locked end end 

Alternatively, can you implement readonly? on the model:

 class Thing < ActiveRecord::Base def readonly? whatever_logic_makes_it_locked || super end end 

this approach will throw an exception instead of a validation error. I think it depends on what you are trying to do, which approach is better.

+4
source

Source: https://habr.com/ru/post/1368877/


All Articles