【问题标题】:rails setting form_for id attribute causes: Couldn't find Folder with 'id'=add_clientrails设置form_for id属性导致:找不到'id'=add_client的文件夹
【发布时间】:2014-10-17 17:03:00
【问题描述】:

我有一个 form_for,如下所示:

  <div class="modal-body">
    <%= form_for @folder, url: add_client_folders_path, html: { id: "add_client" }   do |f| %>
      <%= f.fields_for :client_profiles do |client_builder| %>
          <%= client_builder.select :id, @clients.collect {|client| [ client.name, client.id ] }, { include_blank: true }, {class: "form-control"} %>
      <% end %>
    <% end %>
  </div>
  <div class="modal-footer">
    <%= submit_tag "Add Client", class: "btn btn-primary", form: "add_client" %>
  </div>

提交表单时,params hash 如下所示:

参数:{"utf8"=>"✓", "authenticity_token"=>"7qxjMI1H/+uMP4qZWwG4lHxdrBBM1z", "folder"=>{"client_attributes"=>{"0"=>{"id"=> "25"}}}, "commit"=>"添加客户端", "id"=>"add_client"}

它给了我以下错误:

Couldn't find Folder with 'id'=add_client

为什么 Rails 在 hash 中提交 html id 属性会导致这个错误?

即使我删除了 id,它仍然给我这个错误。路线如下所示:

  resources :folders do
    post :add_client, on: :collection
  end

当我明确声明 post 方法时,它提交正常:

method: :post 

但是为什么我必须在这里指定方法 post 呢?

【问题讨论】:

  • 我认为问题在于@folder 是现有记录,因此它尝试将方法转换为put,从而导致该错误。

标签: ruby-on-rails


【解决方案1】:

对于未来的读者,我有一个比创建单独的资源路径更好的主意。您可以继续重复使用 update restful 资源,因为新的关联会在您更新现有记录时自动保存:

 <%= form_for @folder do |f| %>
   <%= f.fields_for :client_profiles, f.object.client_profiles.build do |client_builder| %>
     <%= client_builder.select :id, @clients.collect {|client| [ client.full_name, client.id ] }, { include_blank: true }, {class: "form-control"} %>
      <%= f.submit "Add Client", class: "btn btn-primary" %

>

【讨论】:

    猜你喜欢
    • 2021-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-28
    • 2015-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多