仅更新一个属性时,是否应该使用强参数? [英] Should we use strong params when we update only one attribute?

查看:80
本文介绍了仅更新一个属性时,是否应该使用强参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Rails应用程序,并且我有几个动作(#delete_later,#ban_later等),其中我仅从请求参数中设置了一个属性(具体来说就是用于执行该动作的reason字段).

I'm working on a Rails app and I have several actions( #delete_later, #ban_later and so on) where I only set one attribute from the request parameter( specifically, a reason field for doing that action).

我想知道是否可以这样做:

I was wondering if it is ok to do it like this:

def ban_later
  @object.reason = params[:object][:reason]
  @object.save
end

还是在这种情况下使用强参数的最佳实践?

Or is it a best practice to use strong params even in this situation?

def ban_later
  @object.reason = object_params[:reason]
  @object.save
end

private
  def object_params
    params.require(:object).permit(:permitted_1, :permitted_2, :reason)
  end

以下哪种解决方案是最佳解决方案?如果它们都不是,那么解决我的问题的最佳解决方案是什么?

Which of these solutions is the best one? If none of them is, then what's the best solution to my problem?

以后的修改:

#ban_later,#delete_later操作确实可以设置标志列status,但这可以在不从params哈希接收其值的情况下完成.由于每种方法只会设置一个状态,因此您只需在#delete_later中设置状态为"pending_delete",而在#ban_later中设置状态为"pending_ban".

The #ban_later, #delete_later actions can indeed set a flag column status but that can be done without receiving it's value from the params hash. Since you will only set one status per method you can simply set the status "pending_delete" when you are in #delete_later and "pending_ban" when you are in #ban_later.

稍后编辑

为什么直接使用#save而不直接使用update_attributes?假设您需要一个if @object.save语句.在false分支(未保存对象)上,您可能仍想渲染一个使用该@object内容的视图.

Why use #save and not update_attributes directly? Let's say you need to have a if @object.save statement. On the false branch( object not saved) you might still want to render a view where the contents of that @object are used.

推荐答案

在设置了强大的参数之后,检查为什么不只是update对象?它只是一个标准的工作流程. (请告诉我您是否有任何理由不这样做)

After strong parameters check why not just update the object? Its just a standart workflow. (Please tell me if there are any reasons not to do that in your situation)

def ban_later
  @object.update(object_params)
  # dont forget validation check
end

private
  def object_params
    params.require(:object).permit(:permitted_1, :permitted_2, :reason)
  end

在这种情况下,添加更多可更新字段会容易得多.

In this case it'd be much easier to add more updateble fields.

这篇关于仅更新一个属性时,是否应该使用强参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆