无法删除Rails 5中的嵌套资源

时间:2018-12-25 14:28:42

标签: ruby-on-rails database

我有两个表,recipy和recipe_ingredients,recipe_ingredients被设置为嵌套资源

resources :recipies do
 resources :recipe_ingredients
end

recipy_ingredients显示在我的recipy_edit页面上,我也想从那里删除它们。 我的修改视图:

 <% @recipe_ingredients.each do |ing| %>
  <p> <%= ing.amount %> <%= ing.unit %> <%= ing.ingredient.try(:ing_name) %> </p>
  <p><%= link_to ('<i class="material-icons"> clear </i>').html_safe, recipy_recipe_ingredient_path(ing.recipy, ing),
               method: :delete, data: {confirm: 'Are you sure?'} %>
</p>
<% end %>
</div>

我的def编辑来自recipies_controller:

def edit
 @recipy = Recipy.find(params[:id])
 @recipe_ingredients = @recipy.recipe_ingredients
end

def从recipe_ingredients控制器中销毁:

def destroy
 @recipe_ingredient = RecipeIngredient.find(params[:id])
 recipy = @recipe_ingredient.recipy
 @recipe_ingredient.destroy
 redirect_to recipy
end

当尝试打开编辑页面时,我不断收到错误消息:

没有路由匹配{:action =>“ show”,:controller =>“ recipe_ingredients”,:id => nil,:recipy_id =>“ 160”},缺少必需的键:[:id]

,此行突出显示:

  <p><%= link_to ('<i class="material-icons"> clear </i>').html_safe, recipy_recipe_ingredient_path(ing.recipy, ing),

这条路线搞砸了吗?我以为这是嵌套资源的正确语法?任何帮助,将不胜感激。谢谢。让我知道您需要任何其他信息!

编辑

经过一番挖掘后,我发现如果在编辑视图中的link_to之前删除了一部分,则代码可以正常工作。 我的部分代码之前:         

添加新成分

    <%= form_with model:[@recipy, @recipy.recipe_ingredients.build]  do |form| %>

      <div class="field">
        <%= form.label :amount %>
        <%= form.text_field :amount %>
      </div>

      <div class="field">
        <%= form.label :unit %>
        <%= form.text_field :unit %>
      </div>

      <div class="field">
        <%= form.select(:ingredient_id, options_from_collection_for_select(Ingredient.all, :id, :ing_name))%>
      </div>

      <div class="actions">
        <%= form.submit "add ingredient", remote: true %>
      </div>

    <% end %>

和为配方名称的def创建

   def create
      @recipy = Recipy.find(params[:recipy_id])
      @recipe_ingredient = @recipy.recipe_ingredients.new(recipe_ingredient_params)

      respond_to do |f|
        if @recipe_ingredient.save
          @recipe_ingredients = @recipy.recipe_ingredients.last
          # f.html
          # f.json
          f.js { render :template => "/recipies/updatingview.js.erb", layout: false}

        end
      end
    end

为什么这会弄乱删除功能?如果删除此部分,则删除实际上有效。有意见吗?

1 个答案:

答案 0 :(得分:0)

每当您使用嵌套表单时,您都需要以这种方式声明表单以进行编辑和新建

<%= form_with(model: [recipe_ingredient.recipy, recipe_ingredient], local: true) do |form| %>

但是局部和形式变得棘手。请注意方括号:

<%= form_for [@recipy, @recipe_ingredient] do |f| %>

最重要的是,如果您需要URI,则可能需要以下内容:

recipy_recipe_ingredient_path(@recipy, @recipe_ingredient)

或者:

[@recipy, @recipe_ingredient]