本文介绍了如何从 params[:something] 中删除一个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的注册表单是用户模型的表单,它采用公司的字符串值.但是,我刚刚进行了更改,使用户属于公司.因此,我需要将 Company 的对象传递给 Users 模型.

My registration form, which is a form for the Users model, takes a string value for company. However, I have just made a change such that users belongs_to companies. Therefore, I need to pass an object of Company to the Users model.

我想使用表单中的字符串值来获取 Company 的对象:

I want to use the string value from the form to obtain the an object of Company:

@user.company = Company.find_by_name(params[:company])

我相信上述方法有效,但是当我调用时,表单将 :company(它是字符串)传递到模型中:

I believe the above works, however the form is passing the :company (which is string) into the model when I call:

@user = User.new(params[:user])

因此,我想知道(并且找不到如何)在将 :company 参数传递给 User 模型之前删除它.

Therefore, I want to know (and cannot find how) to remove the :company param before passing it to the User model.

推荐答案

Rails 4/5 - 已编辑的答案(见评论)

自从编写这个问题以来,较新版本的 Rails 添加了 extract!except 例如:

Since this question was written newer versions of Rails have added the extract! and except eg:

new_params = params.except[the one I wish to remove]

这是一种更安全的方法,可以将您需要的所有参数抓取"到副本中,而不会破坏传入的原始参数(这不是一件好事,因为随着时间的推移,它会使代码的调试和维护变得非常困难).

This is a safer way to 'grab' all the params you need into a copy WITHOUT destroying the original passed in params (which is NOT a good thing to do as it will make debugging and maintenance of your code very hard over time).

或者你可以直接通过而不复制,例如:

Or you could just pass directly without copying eg:

@person.update(params[:person].except(:admin))

extract!(有 !bang 操作符)会修改原来的,所以使用时要小心!

The extract! (has the ! bang operator) will modify the original so use with more care!

原答案

您可以使用 Hash#delete 从哈希中删除键/值对:

You can remove a key/value pair from a Hash using Hash#delete:

params.delete :company

如果它包含在 params[:user] 中,那么你会使用这个:

If it's contained in params[:user], then you'd use this:

params[:user].delete :company

这篇关于如何从 params[:something] 中删除一个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 09:57