Rails发布参数名称语法?

问题描述 投票:0回答:2

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

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

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

"controller_name[attribute_name]"

经过大量的尝试,我甚至发现嵌套的哈希参数可以传递为:

"controller_name[attribute_name][attribute_name]"

我的问题是我有has_many嵌套属性,我没有设法找出rails期望嵌套记录数组的语法。另外我很高兴知道我怎么能传递一些东西来说我要销毁一个嵌套的记录。

我正在使用Rails 5.1 BTW

ruby-on-rails ruby post
2个回答
0
投票

通常当您使用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

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 %>
© www.soinside.com 2019 - 2024. All rights reserved.