2017-09-09 9 views
0

recipe_ingredientsからhas_many recipe_ingredientsとhas_many ingredientsを持つレシピがあります。レシピコントローラのrecipe_ingredientsテーブルのレコードを編集しようとしています。私が持っているフォームでは、編集のためのすべてのフィールドがリストされています(私はただ一つだけを必要とします)。もう一つは、レコードを更新していないということです。あなたがこの問題に出くわすことができる光のために、事前にありがとう。ここに編集フォームがあります。そのテーブルの結合テーブルのレコードを編集しています

<%= 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 
+0

レコードが更新されないという問題はおそらく、recipe_paramsメソッドの結果です。親レコードを使用して子レコードを更新するには、子レコードのどの属性を許可するかを指定する必要があります。あなたのスキーマを表示することができれば、私はそれを手伝ってくれるでしょう。 – moveson

答えて

0

ない最良の方法が、私はルートに:recipe_ingredientsを追加し、編集を移動しingredients_controllerに作成するには、笑、このスーパー醜いpath_helperを追加しました。

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 

私は笑、私はjsutそう揚げだし、これを行うにはもっと良い方法があると確信しています。