Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/475.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/60.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 处理嵌套表单中的许多隐藏字段_Javascript_Ruby On Rails_Autocomplete_Nested Forms_Cocoon Gem - Fatal编程技术网

Javascript 处理嵌套表单中的许多隐藏字段

Javascript 处理嵌套表单中的许多隐藏字段,javascript,ruby-on-rails,autocomplete,nested-forms,cocoon-gem,Javascript,Ruby On Rails,Autocomplete,Nested Forms,Cocoon Gem,我有一个has\u many-through关联,我得到了一个错误,因为我没有将:component\u id作为数组传递(或者类似的,这只是一个猜测:) 错误:无法找到ID为1的成分,用于ID为的测量成分。 Parameters: {"utf8"=>"✓", "authenticity_token"=>"oJQaOCcVavXpWTs4Zz88TWrBchkf7315AnxCJgoYGnpzOxqWd3tz1tiSFwZGDPmzVPpzkSDhFGdDY9j5bpoI1Q==

我有一个has\u many-through关联,我得到了一个错误,因为我没有将
:component\u id
作为数组传递(或者类似的,这只是一个猜测:)

错误:
无法找到ID为1的成分,用于ID为的测量成分。

Parameters:

{"utf8"=>"✓",
 "authenticity_token"=>"oJQaOCcVavXpWTs4Zz88TWrBchkf7315AnxCJgoYGnpzOxqWd3tz1tiSFwZGDPmzVPpzkSDhFGdDY9j5bpoI1Q==",
 "meal"=>{"name"=>"",
 "meal_ingredients_attributes"=>{"1450070337804"=>{"ingredient_attributes"=>{"id"=>"1",
 "name"=>"Banana"},
 "ingredient_id"=>"2",     # HERE THE ID IS BEING SENT
 "quantity"=>"0.0",
 "_destroy"=>"false"},
 "1450070339919"=>{"ingredient_attributes"=>{"id"=>"2",
 "name"=>"Grape"},
 "ingredient_id"=>"",      # HERE THERE'S NO ID BEING SENT
 "quantity"=>"0.0",
 "_destroy"=>"false"}}},
 "commit"=>"Create Meal"}
这就是我处理这个嵌套表单的方式:

配料.rb

class Ingredient < ActiveRecord::Base
  has_many :meal_ingredients
  has_many :meals, through: :meal_ingredients


  accepts_nested_attributes_for :meal_ingredients, :reject_if => :all_blank

end
class Meal < ActiveRecord::Base

  has_many :meal_ingredients
  has_many :ingredients, through: :meal_ingredients
  accepts_nested_attributes_for :ingredients, :reject_if => :all_blank, :allow_destroy => true
  accepts_nested_attributes_for :meal_ingredients

end
class MealIngredient < ActiveRecord::Base
  belongs_to :meal
  belongs_to :ingredient
  accepts_nested_attributes_for :ingredient, :reject_if => :all_blank

end
<div class = "row">
  <div class= "col-md-10 col-md-offset-1">
    <%= simple_form_for(@meal) do |f| %>
      <%= f.error_notification %>
      <div class="form-inputs">
        <%= f.input :name %>
      </div>
      <h3>ingredientes</h3>
      <fieldset id="ingredients">
        <ol>
          <%= f.fields_for :meal_ingredients do |meal_ingredient| %>
            <%= render "meal_ingredient_fields", :f => meal_ingredient  %>
          <% end %>
        </ol>

        <div class="form-actions">
          <div><%= link_to_add_association 'adicionar ingrediente', f, :meal_ingredients, 'data-association-insertion-node' => "#ingredients ol", 'data-association-insertion-method' => "append", :wrap_object => Proc.new {|quantity| quantity.build_ingredient; quantity }, :class => "btn btn-default" %></div>
        </div>
      </fieldset>
      <div class="form-actions">
        <div><%= f.button :submit, class: "btn btn-success" %></div>
      </div>
    <% end %>
  </div>
</div>
<div class = "nested-fields">
  <table class= "table">
      <thead>
        <tr>
          <td>
            <%= f.label "Nome" %>
          </td>
          <td>
            <%= f.label "Unidade" %>
          </td>
          <td>
            <%= f.label "Carbo" %>
          </td>
          <td>
            <%= f.label "Prot" %>
          </td>
          <td>
            <%= f.label "Gordura" %>
          </td>
          <td>
            <%= f.label "Quantidade" %>
          </td>
          <td>
            <%= f.label "kcal" %>
          </td>
        </tr>
      </thead>
      <tbody>
        <tr>
          <%= f.fields_for :ingredient do |fi| %>
            <%= fi.hidden_field :id %>                      ## EDIT 1: THIS LINE WAS REMOVED
            <td scope="row" class="col-md-4">
              <%= fi.autocomplete_field :name, autocomplete_ingredient_name_ingredients_path, :id_element => '#ingredient_id', class: "form-control" %>
            </td>
            <td class="col-md-1">
              <%= fi.text_field :unit, required: true, class: "form-control" %>
            </td>
            <td class="col-md-1">
              <%= fi.text_field :carb, required: true, :pattern => '^\d+(\.\d+)*$', title: "Apenas números separados por pontos", class: "form-control " %>
            </td>
            <td class="col-md-1">
              <%= fi.text_field :prot, required: true, :pattern => '^\d+(\.\d+)*$', title: "Apenas números separados por pontos", class: "form-control " %>
            </td>
            <td class="col-md-1">
              <%= fi.text_field :fat, required: true, :pattern => '^\d+(\.\d+)*$', title: "Apenas números separados por pontos", class: "form-control " %>
            </td>
          <% end %>
          <td class="col-md-1">
            <%= f.hidden_field :ingredient_id %>        ## EDIT 1: FOLLOWING CODE WAS REMOVED:    :id => 'ingredient_id'
            <%= f.number_field :quantity, required: true, :pattern => '^\d+(\.\d+)*$', title: "Apenas números separados por pontos", class: "form-control" %>

          </td>          
          <td class="col-md-1">
          </td>
          <td class="col-md-1">
            <%= link_to_remove_association "remove item", f, :class => "btn btn-danger" %>
          </td>
        </tr>
      </tbody>
  </table>
</div>
class MealsController < ApplicationController
  before_action :set_meal, only: [:edit, :update, :show]


  def index
    @meals = Meal.all
  end

  def show
  end

  def new
    @meal = Meal.new
    @ingredient = @meal.ingredients.build
  end

  def create
    @meal = Meal.new(meal_params)
    if @meal.save
      flash[:success] = "Refeição criada com sucesso!"
      redirect_to meals_path
    else
      render :new
    end
  end

  def edit
  end

  def update
    if @meal.update(meal_params)
      flash[:success] = "Your meal was updated succesfully!"
      redirect_to meal_path(@meal)
    else
      render :edit
    end
  end

  private

    def meal_params
      params.require(:meal).permit(:name, :picture, :tcarb, :tprot, :tfat, :tkcal, meal_ingredients_attributes: [:ingredient_id, :quantity, ingredient_attributes: [:id, :name, :unit, :carb, :prot, :fat, :_destroy]])
    end


    def set_meal
      @meal = Meal.find(params[:id])
    end

end

这个错误看起来很不明显;我不认为这会直接回答你的问题,但我还是要试试看它是否有帮助:

{"utf8"=>"✓",
 "authenticity_token"=>"oJQaOCcVavXpWTs4Zz88TWrBchkf7315AnxCJgoYGnpzOxqWd3tz1tiSFwZGDPmzVPpzkSDhFGdDY9j5bpoI1Q==",
 "meal"=>
    {"name"=>"",
       "meal_ingredients_attributes"=>
          { 
            "1450070337804"=>
               { "ingredient_attributes"=> {"id"=>"1","name"=>"Banana"},
                 "ingredient_id"=>"2",     # HERE THE ID IS BEING SENT
                 "quantity"=>"0.0",
                 "_destroy"=>"false"
               },
            "1450070339919"=>
               { "ingredient_attributes"=> {"id"=>"2", "name"=>"Grape"},
                 "ingredient_id"=>"",      # HERE THERE'S NO ID BEING SENT
                 "quantity"=>"0.0",
                 "_destroy"=>"false"
               }
          }
    },
 "commit"=>"Create Meal"
}

我试图确定你是在制造新的配料,还是在调用现有的配料

您正在使用以下字段:

<%= f.fields_for :ingredient do |fi| %>
    <%= fi.hidden_field :id %>
<% end %>
<%= f.hidden_field :ingredient_id, :id => 'ingredient_id' %>
无需为嵌套记录显式定义
id

<%= f.fields_for :ingredient do |fi| %>
   # remove ID, you don't need it
   <%= fi.text_field :name %>
此外,您的强参数似乎需要调整:

def meal_params
  params.require(:meal).permit(:name, :picture, :tcarb, :tprot, :tfat, :tkcal, meal_ingredients_attributes: [:ingredient_id, :quantity, ingredient_attributes: [:name, :unit, :carb, :prot, :fat, :_destroy]])
end

这可能会帮助您事实上,配料字段中的隐藏字段有一个:id_element=>“#配料_id”。这就是我设置配料id的原因。然而,我正在考虑使用js进行设置,我只是没有,因为我认为这有点“硬编码”。非常感谢,您建议的验证将非常有用:)顺便说一句,您注意到我尝试用HTML5验证我的表单了吗?为什么它不起作用?好吧,因为我在使用gem和autocomplete,所以我制作了一个js来处理id,而且我还想在选择配料时显示配料的所有特性(记住,用户可以创建或查找配料)。我更新了我的问题。问题是:尽管它正确显示了所有数据,但它没有传递参数。
<%= f.fields_for :ingredient do |fi| %>
   # remove ID, you don't need it
   <%= fi.text_field :name %>
#app/models/meal_ingredient.rb
class MealIngredient < ActiveRecord::Base
   validate :ingredient_set

   private

   def ingredient_set 
      errors.add(:ingredient_id, "Need either a new ingredient, or to select one") unless ingredient && ingredient_id.blank?
   end
end
def meal_params
  params.require(:meal).permit(:name, :picture, :tcarb, :tprot, :tfat, :tkcal, meal_ingredients_attributes: [:ingredient_id, :quantity, ingredient_attributes: [:name, :unit, :carb, :prot, :fat, :_destroy]])
end