[英]Rails don't allow attribute to update under a certain condition
Say i'm updating an attribute called status
. 假设我要更新一个名为status
的属性。 I don't want the status
to be able to be able to be updated when it's currently cancelled
or complete
. 我不希望status
在当前cancelled
或complete
时能够被更新。 How could I not allow this, but allow status
to be updated otherwise? 我怎么不能允许它,但是要允许status
以其他方式更新?
You can use a before_update
callback. 您可以使用before_update
回调。
before_update :prevent_update_if_status_canceled_or_completed?
private
def prevent_update_if_status_canceled_or_completed?
if status == 'canceled' || status == 'complete'
self.errors.add_to_base "Cannot update a completed or canceled record "
false
else
true
end
end
You can use the transitions gem . 您可以使用转场gem 。 It's quite neat. 非常整洁。
You can simply check while creating a status for that user. 您可以在为该用户创建状态时简单地进行检查。
def create
@user = User.find(params[:user_id])
unless @user.status == "cancelled" || @user.status == "completed"
@status = @user.statuses.new(status_params)
if @status.save!
respond_to do |format|
...
#status created logic, render desired content to user
end
end
else
#Handle status not created logic
end
end
I guess you've a update
method like: 我猜你有一个像这样的update
方法:
def update
params[:model_name].delete :status if @model_name.status == "cancelled"
@model_name = @model_name.update(model_params) # model_params are the parameters you're allowing with strong parameters.
.....
end
Delete the status
from the strong parameter with a conditional statement. 使用条件语句从strong参数中删除status
。
or, you can create a private
method for excluding the status
from being updated. 或者,您可以创建一个private
方法以将status
排除在更新之外。
def except_satatus_params
params[:model_name].except(:status)
end
then use this method on the controller with a check that if @model.status
is previously cancelled
or complete
. 然后在控制器上使用此方法,并检查@model.status
是否先前cancelled
或complete
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.