ActiveRecord保存:Rails 3.2.19和Rails 4.2.0的差异

时间:2014-11-19 12:09:38

标签: ruby-on-rails ruby activerecord

我有两个相同的项目:使用Rails 3.2.19并更新到Rails 4.2.0beta4。 当我尝试在Rails 3.2和Rails 4.2中执行Foo.create!时,我在Rails控制台日志中看到了不同的查询。

Rails 3.2输出:

INSERT INTO `foos` (`created_at`, `updated_at`, `column_1`,`column_2`, ...) VALUES ('2014-11-19 11:20:28.391649', '2014-11-19 11:20:28.391649', NULL, NULL, ...)

Rails 4.2输出:

INSERT INTO `foos` (`created_at`, `updated_at`) VALUES ('2014-11-19 11:20:28.391649', 545662, '2014-11-19 11:20:28.391649')

请解释为什么不同的Rails版本执行不同的查询以及为什么这样做?

1 个答案:

答案 0 :(得分:0)

这与4.x版本中默认启用的Strong Parameters相关。 以文档为例:

class PeopleController < ActionController::Base
  # This will raise an ActiveModel::ForbiddenAttributes exception because it's using mass assignment
  # without an explicit permit step.
  def create
    Person.create(params[:person])
  end

  # This will pass with flying colors as long as there's a person key in the parameters, otherwise
  # it'll raise an ActionController::ParameterMissing exception, which will get caught by
  # ActionController::Base and turned into that 400 Bad Request reply.
  def update
    person = current_account.people.find(params[:id])
    person.update_attributes!(person_params)
    redirect_to person
  end

  private
    # Using a private method to encapsulate the permissible parameters is just a good pattern
    # since you'll be able to reuse the same permit list between create and update. Also, you
    # can specialize this method with per-user checking of permissible attributes.
    def person_params
      params.require(:person).permit(:name, :age)
    end
end

person_params方法中,您需要允许所有要更改的参数。