나는 이것에 관해서 상상할 수있는 모든 게시물을 살펴 보았지만 해결책을 찾을 수는 없습니다. 나는 다른 데이터베이스에서 ID를 가져 오는 Task Products의 중첩 된 리소스가있는 Task를 가지고있다. Task에 중첩 된 Task Product가 여러 개있을 수 있으며, 각각 하나의 JavaScript와 Application Helper로 동적으로 생성됩니다 (둘 다 순전히 자신의 부분에 복사/붙여 넣기입니다).중첩 된 속성의 허용되지 않은 매개 변수
Railscast 196/197 및 this post의 도움으로 이러한 중첩 매개 변수에 대한 코드를 작성했습니다.
task.rb :
class Task < ApplicationRecord
has_many :task_products, :dependent => :destroy
accepts_nested_attributes_for :task_products, :reject_if => lambda { |p| p.values.all?(&:blank?) }, :allow_destroy => true
end
task_controller.rb :
class TasksController < ApplicationController
def new
@task = Task.new
@task.task_products.build
end
def task_params
params.require(:task).permit(:id, :task_name, . . ., :created_at, :updated_at,
:task_products_attributes => [:task_id, :product_id, :created_at, :updated_at])
end
application_helper.rb :
module ApplicationHelper
def new_child_fields_template(form_builder, association, options = {})
options[:object] ||= form_builder.object.class.reflect_on_association(association).klass.new
options[:partial] ||= association.to_s.singularize
options[:form_builder_local] ||= :f
content_tag(:div, :id => "#{association}_fields_template", :style => "display: none") do
form_builder.fields_for(association, options[:object], :child_index => "new_#{association}") do |f|
render(:partial => options[:partial], :locals => { options[:form_builder_local] => f })
end
end
end
모든 관련 코드는 문제에 다음 아래이며, application.js :
$(function() {
$('form a.add_child').click(function() {
var association = $(this).attr('data-association');
var template = $('#' + association + '_fields_template').html();
var regexp = new RegExp('new_' + association, 'g');
var new_id = new Date().getTime();
$(this).parent().before(template.replace(regexp, new_id));
return false;
});
});
_form.html.erb :
이<%= form_for @task, url: tasks_path, method: :post, :html => {:multipart => true } do |f| %>
<%= f.fields_for :task_products, TaskProduct.new do |builder| %>
<%= render "task_product", :f => builder %>
<% end %>
<p><%= add_child_link "Add Product", :task_products %></p>
<%= new_child_fields_template f, :task_products %>
_task_product.html.erb :
Parameters: {"utf8"=>"✓", "authenticity_token"=>"KDQ...8bxur2A==",
"task"=>{"task_type"=>"Store Order",
"task_products_attributes"=>{
"0"=>{"product_id"=>"1", "_destroy"=>"false"},
"1484792726712"=>{"product_id"=>"2", "_destroy"=>"false"},
"new_task_products"=>{"product_id"=>"", "_destroy"=>"false"}},
"initiated_by"=>"1", "initiated_for"=>"5", "active"=>"true", "status"=>"Pending Acceptance"},
"commit"=>"Create Task"}
Unpermitted parameters: 0, 1484792726712, new_task_products
생성 : 콘솔에서
<div class="fields">
<div class="form-group">
<%= f.label :product_id, "Product:", class: 'col-sm-3 control-label' %>
<%= f.collection_select(:product_id, @items, :id, :item_select, {:include_blank => 'Select Item...'}, {:class => 'form-control'}) %>
<%= remove_child_link "Remove Product", f %>
</div>
</div>
코드 후가 생성되는 오류와 함께 제출 여러 생성 된 코드의 오류 생성 HTML 예제 :
<select class="form-control" name="task[task_products_attributes][0][product_id]" id="task_task_products_attributes_0_product_id">
<select class="form-control" name="task[task_products_attributes][1484794199756][product_id]" id="task_task_products_attributes_1484794199756_product_id">
내가 콘솔? 위에서 볼 수 있듯이
<select class="form-control" name="task[task_products_attributes][new_task_products][product_id]" id="task_task_products_attributes_new_task_products_product_id">
문제,이다의 ' "_destroy"=> 진정한'를 다시 던지는한다고 생각의 템플릿, 내 생성 작업 제품 형태가 각 항목에 대한 선택 상자에 대괄호로 묶인 식별자 (하위 색인?)를 추가하는 중입니다. 응용 프로그램 도우미를 제거하거나 속한 곳으로 이동하는 방법을 모르겠습니다. 아니면 실제로 그곳에 속해 있고 다른 일을 잘못하고 있습니까? 각 개별 작업 제품 은에 고유 한 고유 식별자가 있어야한다는 느낌을 갖지만 레일스는 그 중 하나도 갖고 있지 않으며 허용되지 않는다고 말합니다.
응용 프로그램 도우미의 'new_child_fields_template'은 약간 머리가 많은데 내 작업 제품 양식에 삽입 할 고유 식별자를 얻는 방법을 알고 있지만 "이름 = "내 선택의 필드가 모든 것을 망가 뜨리고있는 것 같습니다. 아무도 내가이 문제를 극복 할 수있는 방법에 대한 지침이 있습니까? 감사!
나는 당신이 이야기하고있는 숨겨진 필드와 비슷한 문제가 있다고 생각합니다. 'CTRL + F'를 누르고이 페이지에서'include_hidden'을 찾으십시오 :'http : // api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html'. 그걸'# collection_check_boxes'에서 param으로 사용할 수 있습니다. '의 =의 collection_check_boxes (: 객체 : 필드, [OPTS] : 방법 항목, :, 방법 2 {include_hidden : 거짓}, &은 – Shiyason
이 도움이된다면 (HTTP [얼마나 강한 매개 변수 배열을 허용하기]를 참조하십시오 block' : //stackoverflow.com/a/30285592/2981429) –
@maxple, 링크를 가져 주셔서 감사합니다 (나중에 유용 할 것입니다!) 그러나 이것이 내가 성취하려고하는 것 같지는 않습니다. 생성 된 코드 응용 프로그램 도우미에서 선택 드롭 다운의 "이름"필드에 추가 값을 넣고 그 값을 양식의 값으로 전달하려고합니다. 값으로 전달할 필요가 없습니다. 필요한 모든 것 해야 할 일은 Task Product가 (자동적으로 일어난다 고 생각되는) Task에 연결되어 있는지 확인하는 것입니다. 그래서 내가해야한다고 생각하는 것은 이름 컬럼에 두 번째로 괄호로 묶은 항목을 없애는 방법을 찾는 것입니다 –