代码之家  ›  专栏  ›  技术社区  ›  Int'l Man Of Coding Mystery

从一个关联编辑连接表上的记录

  •  0
  • Int'l Man Of Coding Mystery  · 技术社区  · 7 年前

    <%= form_for @recipe, remote: true do |recipe_form| %>
      <%= recipe_form.fields_for :recipe_ingredients do |f| %>
        <%= f.label :amount %>
        <%= f.number_field :amount, step: :any %>
    
        <%= f.submit %>
      <% end %>
    <% end %>
    

    和控制器。

    def edit
        @recipe = Recipe.find(params[:id])
        @recipe_ingredients = @recipe.recipe_ingredient
      end
    
      def update
        @recipe = Recipe.find(params[:id])
        @recipe.recipe_ingredients = RecipeIngredient.where(recipe_id: params[:id])
      end
    
    
      private
    
      def recipe_params
        params.require(:recipe).permit(:name, :recipe_ingredient_ids => [], :ingredient_ids => [])
      end
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Int'l Man Of Coding Mystery    7 年前

    不是最好的办法,但我补充说 :recipe_ingredients 将“编辑和创建”路由并移动到 ingredients_controller 添加了这个超级丑陋的path_助手,lol。

    resources :users, only: [:new, :create, :show ]
      resources :recipes, :recipe_ingredients do
        resources :ingredients, only: [:new, :create, :edit, :update]
      end
    
    
    
     <tbody>
          <% @recipe.recipe_ingredients.each do |recipe_ingredient| %>
    
          <tr>
            <td><%#= check_box_tag "recipe_ingredient_ids[]", recipe_ingredient.id %> </td>
            <td><%= recipe_ingredient.ing_name %></td>
            <td><%= recipe_ingredient.amount %> <%= link_to 'Edit Ingredient',
                      edit_recipe_ingredient_ingredient_path(recipe_ingredient) %> </td>
          </tr>
          <% end %>
    
      </tbody>
      </table>
    

    def update
        @recipe = Recipe.find(params[:id])
        recipe_ingredient = RecipeIngredient.find(params[:recipe_id])
        recipe_ingredient.update(amount: params[:recipe_ingredient][:recipe_ingredients][:amount].to_f)
        # require "pry"; binding.pry
        redirect_to recipe_path(@recipe)
      end