开发者

How to "lock" a record from being updated or deleted?

I have a model User which automatically has a Task开发者_高级运维 generated.

I want to lock this task from editing or deleting.

What kind of modifications to my controller do I need to make? Is there an elegant solution, or do I need to check every time there's an edit/destroy if it's the task in question.


You can use a validation to do this quite nicely.

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, you can implement readonly? on the model:

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

this approach will raise an exception instead of a validation error. I guess it depends on what you're trying to do as to which approach is better.


There is no elegant solution as far as I am aware, you would have to check every time in the controller, but this is simple by defining 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

Then you can call this method as a before_filter for those actions you care about. By returning nil (that's what return does), the before_filter will halt and the action will not be executed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜