【问题标题】:Rails post parameters name syntax?Rails发布参数名称语法?
【发布时间】:2017-12-17 11:16:22
【问题描述】:

我正在尝试找出嵌套属性的输入字段名称的格式。假设我有一个带有输入字段的编辑操作:

<input type="text" name="...">

我发现参数名称的语法是:

"controller_name[attribute_name]"

经过大量尝试,我什至发现嵌套散列参数可以传递为:

"controller_name[attribute_name][attribute_name]"

我的问题是我有 has_many 嵌套属性,但我没有设法找出嵌套记录数组所期望的语法轨道。 另外,很高兴知道如何传递一些内容来表示我想销毁嵌套记录。

我正在使用 Rails 5.1 顺便说一句

【问题讨论】:

  • 为什么不使用 Rails 表单助手为您生成预期名称?

标签: ruby-on-rails ruby post


【解决方案1】:

我相信它是这样的:

<input name="user[posts_attributes][0][id]" value="5" />
<input name="user[posts_attributes][0][body]" value="You've given me too much to feel" />

<input name="user[posts_attributes][1][id]" value="8" />
<input name="user[posts_attributes][1][body]" value="You've almost convinced me I'm real" />

记得将这个添加到你的用户模型中:

class User < ApplicationRecord
  has_many :posts

  accepts_nested_attributes_for :posts
end

我通常使用 SimpleForm 来简化此操作:

<%= simple_form_for @user do |f| %>
  <%= f.simple_fields_for :posts do |f_post| %>
    <%= f_post.input :body %>
  <% end %>
<% end %>

【讨论】:

    【解决方案2】:

    通常当你使用 has_many 时,它在父模型中会有 accept_nested_attributes。

    例如

    Class Book 
      has_many :pages 
    
      accepts_nested_attributes_for :pages
    End
    

    所以在视图中会是这样的

    <input name="book[pages_attributes][0][id]" type="hidden" value="1" />
    <input name="book[pages_attributes][0][name]" type="text" />
    <input name="book[pages_attributes][1][id]" type="hidden" value="2" />
    <input name="book[pages_attributes][1][name]" type="text" />
    

    销毁你有一个隐藏的输入

    <input name="book[pages_attributes][0][_destroy]" value="true" type="hidden" />
    

    当你这样做时,这将很容易更新 Book 对象和页面

    @book.update_attributes
    

    【讨论】:

    • 谢谢!但是 0 是什么意思?身份证?只是每个记录必须不同的数字?如何让 Rails 销毁现有记录?
    • 0 表示与 Book 相关的第一个页面对象
    • 更新了我的答案,让您更好地理解
    • 你是否在接受嵌套属性中添加了allow_destroy
    • 谢谢!你忘了写在你的答案中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-06
    • 1970-01-01
    • 2011-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-10
    相关资源
    最近更新 更多