加入table个数量带茧(has_many个通过)

Join table Quantity with cocoon (has_many through)

我没有找到与我的问题相关的任何内容。 我有这些型号:

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 Ingredient < ActiveRecord::Base
  has_many :meal_ingredients
  has_many :meals, through: :meal_ingredients
end

class MealIngredient < ActiveRecord::Base
  belongs_to :meal
  belongs_to :ingredient
end

在 meal_ingredient 模型中,我有一个 数量 列,我想让用户在创建包含许多成分的新餐时设置此数量。为此,我使用了 cocoon gem。这就是问题来的时候:我必须设置 ingredient_idmeal_id 来建立与数量的关联,但我只是在提交 "Create Meal" 按钮时访问了数据库。 我认为的部分解决方案是在表单中创建一个 fields_for 并在控制器中设置一个实例变量。
但是我怎样才能得到这些ID?我卡住了。

class MealsController < ApplicationController
  before_action :set_meal, only: [:edit, :update, :show]
  autocomplete :ingredients, :name

  def index
    @meals = Meal.order(updated_at: :desc).paginate(:page => params[:page], :per_page => 4)
  end

  def show
  end

  def new
    @meal = Meal.new
    @qtd = MealIngredient.new
  end

  def create
    @meal = Meal.new(meal_params)
    @qtd = @meal.ingredients.map{|r| MealIngredient.new(quantity: params[:quantity], ingredient_id: r.id, meal_id: @meal)}
    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, ingredients_attributes: [:name, :unit, :carb, :prot, :fat])
    end


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

end

这是我目前得到的...我不认为主要问题是由茧引起的 gem。我认为这是关于概念的...

参数

Parameters: {"utf8"=>"✓", "authenticity_token"=>"dTYOiz8+pwNfwt432qhy7Yuj0hSVksj0bsTzxp8vD6QaupIJueSO1ASDkwiOB92qCiLO33Ke61aUBGbyvGZJfA==", "meal"=>{"name"=>"tests", "ingredients_attributes"=>{"1449471543091"=>{"name"=>"uva", "unit"=>"und", "carb"=>"1", "prot"=>"1", "fat"=>"1", "_destroy"=>"false"}}}, "meal_ingredient"=>{"quantity"=>"14"}, "commit"=>"Create Meal"}

查看 _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>
      <div id="ingredients">
        <%= f.simple_fields_for :ingredients do |ingredient| %>
          <%= render "ingredient_fields", :f => ingredient %>
        <% end %>
      </div>

      <div class="form-actions">
        <div><%= link_to_add_association 'adicionar ingrediente', f, :ingredients, :class => "btn btn-default" %></div>

        <div><%= f.button :submit, class: "btn btn-success" %></div>
      </div>
    <% end %>
  </div>
</div>

_ingredient_fields.html.erb

<%= render 'shared/errors', obj: @meal %>
<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>
          <td scope="row" class="col-md-4">
            <%= f.text_field :name, required: true, class: "form-control" %>
          </td>
          <td class="col-md-2">
            <%= f.text_field :unit, required: true, class: "form-control" %>
          </td>
          <td class="col-md-1">
            <%= f.text_field :carb, required: true, :pattern => '^\d+(\.\d+)*$', title: "Apenas números separados por pontos", class: "form-control" %>
          </td>
          <td class="col-md-1">
            <%= f.text_field :prot, required: true, :pattern => '^\d+(\.\d+)*$', title: "Apenas números separados por pontos", class: "form-control" %>
          </td>
          <td class="col-md-1">
            <%= f.text_field :fat, required: true, :pattern => '^\d+(\.\d+)*$', title: "Apenas números separados por pontos", class: "form-control" %>
          </td>
          <td class="col-md-1">
            <%= fields_for @qtd do |f| %>
              <%= f.hidden_field :ingredient_id %>
              <%= f.number_field :quantity, required: true, :pattern => '^\d+(\.\d+)*$', title: "Apenas números separados por pontos", class: "form-control" %>
            <% end %>
          </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>

我也用过 cocoon,但在设置时遇到了一些麻烦。我认为你必须意识到 Rails 比你想象的更聪明。您可以轻松地在参数字符串上调用保存。只要确保所有参数都被接受。例如,您还需要 :id 表示 ingredients_attributes(以及 :_destroy,如果您也允许删除)。哦,还有为你的加入 table 松开 nested_attributes。

我认为这样的事情应该可行:

  def new
    @meal = Meal.new
  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
private

    def meal_params
      params.require(:meal).permit(:name, :picture, ingredients_attributes: [:id, :name, :unit, :carb, :prot, :fat, :_destroy])
    end

如果没有,请post您包含主要形式和部分形式的视图。

正在关注 this tutorial and looking at the cocoon's demo 个应用。很容易解决我的问题,虽然我实际上并不知道我在这里做了什么
<%= 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" %>
我讨厌这样编码,但这次我非常小心地顺其自然...
如果有人已经为此目的使用了 cocoon 并且可以更好地解释我 - 以及社区 - 将不胜感激:D
所做的更改:
型号

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

控制器

class MealsController < ApplicationController
  before_action :set_meal, only: [:edit, :update, :show]
  autocomplete :ingredients, :name

  def index
    @meals = Meal.order(updated_at: :desc).paginate(:page => params[:page], :per_page => 4)
  end

  def show
  end

  def new
    @meal = Meal.new
  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: [:quantity, ingredient_attributes: [:id, :name, :unit, :carb, :prot, :fat, :_destroy]])
    end


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

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| %>
          <td scope="row" class="col-md-4">
            <%= fi.text_field :name, required: true, class: "form-control" %>
          </td>
          <td class="col-md-2">
            <%= 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.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>