Rails 4 强参数 [英] Rails 4 strong parameters

查看:36
本文介绍了Rails 4 强参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rails 4 如何处理强参数似乎很有趣:

It seems to be funny how Rails 4 deals with strong parameters:

def UsersController < ActionController::Base
  def update
    @user = current_user

    if @user.update_attributes(user_profile_parameters)
      redirect_to home_path, notice:  "Your profile has been successfully updated."
    else
      render action: "edit"
    end
  end

  private
  def user_profile_parameters
    params.require(:user).permit(:name, :password, :password_confirmation, :email)
  end
end

我想知道,在 Rails 3 中不能实现吗?是的,而不是只有 1 行,它可能需要 3 行.但是,那里没有什么新东西,它只是一个手动创建的允许参数列表,事实上,它只是一个散列,不是吗?或者它还有更深层的目的吗?

I wonder, isn't it possible in Rails 3? Yes, instead of only 1 line, it would take 3 lines, perhaps. But, there is nothing new there, it's just a manually created list of allowed parameters, in fact, it's just a hash, isn't it? Or is there any more deep purpose in it?

推荐答案

我猜它在 rails 4 作为一个单独的 gem 发布之前就已经存在了https://github.com/rails/strong_parameters

I guess it existed way(way way before) before the release of rails 4 as a separate gem https://github.com/rails/strong_parameters

rails 4 默认有它,如果你想将它与 rails 3 一起使用,只需在你的 gemfile 中获取 gem 并开始:)

rails 4 have it by default ,if you want to use it with rails 3 , just get the gem in your gemfile and get going :).

在 gem 的 github 链接上,他们也写了关于如何使用它的很棒的文档,所以我想你使用它应该没有任何问题.

on the github link of the gem , they also have written awesome documentaion on how to use it , so i guess you should not have any problems using it.

当然里面没有什么新东西,您可以通过编写自己的过滤器来手动执行此过滤,如果散列的键是动态创建的(不固定),则使用深度嵌套的散列和散列中的数组可能会有点棘手

And ofcourse there is nothing new in it , you can do this filtering manually by writing your own filters and things may get a bit tricky with deeply nested hashes and array inside the hashes and if the keys of the hashes are dynamically created(not fixed)

""是的,而不是只有 1 行,它需要 3 行"" 这就是大多数 gem 所做的,我们使用它们而不是重新发明轮子并专注于我们的业务逻辑.

""Yes, instead of only 1 line, it would take 3 lines"" and thats what most of the gems do , and we use them instead of reinventing the wheel and just concentating on our business logic.

这篇关于Rails 4 强参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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