【问题标题】:Are these 2 different ways of writing nested attributes in strong params?这两种在强参数中编写嵌套属性的不同方式吗?
【发布时间】:2015-03-19 17:56:21
【问题描述】:

我正在使用嵌套属性和强参数,我已经看到了在强参数中嵌套属性的两种不同方式。

举个例子:

class Post < ActiveRecord::Base
has_many :comments
accepts_nested_attributes, :comments

class Comments < ActiveRecord::Base
belongs_to :post

在Post Controller中看到了这两种cmet嵌套参数的方式,有区别吗?

params.require(:post)
      .permit(:title, :id, :author, :comment => [:id, :content, :post_id, :user_id])

params.require(:post)
      .permit(:title, :id, :author, comments_attributes: [:id, :content, :post_id, :user_id])


它们看起来很相似......通常我会认为一个是早期版本,但我相信强参数是相对较新的。有什么区别?

【问题讨论】:

  • 从未见过它们被这样使用。第二个是应该的。它们都有效吗?
  • 我只用过第二个成功。我在这里获得了代码,因此使用了第一个代码并且代码不起作用。我太新了,看不出差异是否与参数、我的无知或新代码有关。此外,这个答案使用第一个......虽然它实际上可能不是nested_attributes:stackoverflow.com/questions/18436741/…

标签: ruby-on-rails ruby-on-rails-4 nested-attributes strong-parameters


【解决方案1】:

Ruby 中只有两种不同的哈希语法

params.require(:post).permit(:title, :id, :author, :comments_attributes => [:id, :content, :post_id, :user_id])

params.require(:post).permit(:title, :id, :author, comments_attributes: [:id, :content, :post_id, :user_id])

都是一样的

当您添加accepts_nested_attributes_for :comments 时,它会创建一个 cmets_attributes 方法。 cmets 方法将需要一个数组,不确定如果您向它发送 cmets 参数它会做什么,也许什么都没有。指向其他“嵌套参数”示例的链接与 accepts_nested_attributes 不同。

【讨论】:

  • 谢谢!其中之一是首选吗?我似乎更经常看到第二个,它看起来更像 Rails 4。
  • 第二个。第一种方法不是特殊约定,它只是将哈希传递给模型中的方法的一种方法(在这种情况下,方法是comment=(hash)。您可以通过 params 传递任何内容并让服务器处理它。在链接到示例,他们只是发送在服务器上解析和处理的 json,调用一堆 setter。如果你真的想要nested_attributes 以及随之而来的所有东西,它总是'obj_attributes'约定。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-08
  • 1970-01-01
  • 1970-01-01
  • 2013-07-22
  • 1970-01-01
  • 2011-11-11
  • 1970-01-01
相关资源
最近更新 更多