gpt4 book ai didi

ruby-on-rails - 请为 params(strong_parameters) 使用新的推荐保护模型或将 `protected_attributes` 添加到您的 gemfile

转载 作者:行者123 更新时间:2023-12-04 03:46:52 25 4
gpt4 key购买 nike

当我将 attr_accessible 添加到我的关系模型时发生这种情况。

class Relationship < ActiveRecord::Base
attr_accessible :followed_id
end

如果不使用 Devise 或 protected_attributes gem,有什么方法可以解决这个问题?我知道在 Controller 中你调用一个私有(private)方法需要和允许字段。这也是你应该在模型中做的事情吗?这里的约定是什么?

谢谢!

最佳答案

在 Rails 4 中,您使用强参数而不是 protected 属性。 (您不需要在 gemfile 中包含 gem,因为它已经包含在内。)

您将 Rails 3 attr_accessible 代码从模型中取出,并将相应的代码放入 Controller 中。有关更多文档,请参见此处:https://github.com/rails/strong_parameters

在您的情况下,类似于:

class RelationshipController < ActionController::Base
def create
@relationship = Relationship.new(relationship_params)

if @relationship.save
# do something
else
# do something
end
end

private
def relationship_params
params.require(:relationship).permit(:followed_id)
end
end

编辑:

这是我刚刚看到的一篇很好的文章: http://blog.sensible.io/2013/08/17/strong-parameters-by-example.html

关于ruby-on-rails - 请为 params(strong_parameters) 使用新的推荐保护模型或将 `protected_attributes` 添加到您的 gemfile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19130184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com