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

时间:2015-12-14 05:34:22

标签: javascript ruby-on-rails autocomplete nested-forms cocoon-gem

我有一个has_many通过关联,我收到一个错误,因为我没有将:ingredient_id作为一个数组传递(或类似的东西,这只是猜测:))

错误: Couldn't find Ingredient with ID=1 for MealIngredient with 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"}

这就是我处理这个嵌套形式的方式:

Ingredient.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

Meal.rb

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

MealIngredient.rb

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

end

_form.html.erb

<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>

_meal_ingredient_fields.html.erb

<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>

最后,控制器: 的 meals_controller.rb

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

请帮助,这让我很头疼:D

编辑


ingredients.js我用来收集当前由cocoon设置的id,并在自动完成时选择一个成分时应用到字段中。

 $(function(){
  var num;
  var id;
  $('#ingredients').on('cocoon:after-insert', function(e, insertedItem) {
    $('input[id^="meal_meal_ingredients_attributes_"][id$="_ingredient_attributes_name"]').each(function(){
        var current = $(this);
        var rx = /meal_meal_ingredients_attributes_(.*)_ingredient_attributes_name/;
        num = rx.exec(current.attr('id'))[1];
        id = '#meal_meal_ingredients_attributes_'+ num +'_ingredient_';
    });
    $(id + 'attributes_name').bind('railsAutocomplete.select', function(event, data){
      $( id + 'id' ).val( data.item.id);
      $( id + 'attributes_unit' ).val( data.item.unit).prop('disabled', true);
      $( id + 'attributes_carb' ).val( data.item.carb).prop('disabled', true);
      $( id + 'attributes_prot' ).val( data.item.prot).prop('disabled', true);
      $( id + 'attributes_fat' ).val( data.item.fat).prop('disabled', true);
    });

  });
}); 

1 个答案:

答案 0 :(得分:2)

错误看起来很不明显;我不认为这会直接回答你的问题,但无论如何我都会试一试,看看它是否有帮助:

{"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' %>

ingredient_id会建议您调用现有成分; id字段表示您正在尝试创建新字段。这可能是出现错误的地方。

  
      
  1. 为什么要为id设置ingredient
  2.   
  3. 为什么您在ingredient_id上提及meal_ingredient
  4.   

我个人会为新成分摆脱id,并使ingredient_id取决于您是否有新成分(如果您创建新的嵌套记录,它会自动设置) 。

我还要确保ingredient_attributes只有在填写完毕后才会被接受(我认为您已经填写):

#app/models/meal_ingredient.rb
class MealIngredient < ActiveRecord::Base
   accepts_nested_attributes_for :ingredient, reject_if: :all_blank
end

不需要为嵌套记录明确定义id

<%= f.fields_for :ingredient do |fi| %>
   # remove ID, you don't need it
   <%= fi.text_field :name %>

要管理ingredient_id vs ingredient_attributes的事情,您可能必须在前端使用JS(如果需要,我会用此更新答案);可以使用以下方法处理后端:

#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