2017-09-08 20 views
0

私はRecipeモデルとIngredientモデルを持っています。それらは両方ともhas_many :recipe_ingredientsおよびレシピhas_many :ingredients, through: recipe_ingredientsおよび成分has_many :recipes, through: recipe_ingredientsおよびレシピエントbelongs_toレシピおよび成分の両方である。 recipe#showから来て私はlink_tonew_recipe_ingredient_path(@recipe)を持っています。そのビューでは、私は私がRecipeIngredientテーブルにレコードを作成するために私ingredients_controllerに何が必要か、他の2つのテーブルから結合テーブルのレコードを作成

<%= form_for @recipe_ingredient do |f| %> 
    <%= f.collection_select :ingredient_id, Ingredient.all, :id, :name %> 

    <%= f.label :amount %> 
    <%= f.number_field :amount %> 
    <%+ f.submit %> 
<% end %> 

私の質問はありますか?私はparamsでシャベルを試みました。私は、IngredientコントローラーでRecipeIngredientを作成し、禁止された属性エラーを取得しようとしました。私は他のことを試して、タイプミスマッチを取得します。 REcipeINgredientコントローラのcreateメソッドにリダイレクトしてそこに作成できるかどうかは疑問です。

答えて

0

「あなたのingredients_controllerでRecipeIngredientテーブルにレコードを作成するには、何が必要ですか?」という質問に基づいています。あなたのコードは反対であるレシピから食材を作成しようとしているが、私はあなたの質問を達成しようとしていることを前提としていますので、ここにある:

変更したり、コントローラでこれを追加し

class IngredientsController < ApplicationController 
def ingredient_params 
params.require(:ingredient).permit(
    :id, 
    :your_attributes_here, 
    {:recipe_ids => []} 
end 
end 

あなたのビューで:

<%= form_for @ingredient do |f| %> 
<%= f.collection_select :recipe_ids, Recipe.all, :id, :name, {}, { multiple: true } %> 
<% end %> 
1

申し訳ありませんが、私はそれらの両方を試してみましたが、うまくいきませんでした。私の新しいform-forは、私が持っている以外は非常に似ています、私はそれはきれいではありません知っているが、それは、働く

def new 
    @recipe = Recipe.find(params[:recipe_id]) 
    @ingredient = Ingredient.new 
    @recipe_ingredient = RecipeIngredient.new 
end 

def create 
    @recipe = Recipe.find(params[:recipe_id]) 
    @ingredient = Ingredient.find(params[:recipe_ingredient][:ingredient_id]) 
    @recipe_ingredient = RecipeIngredient.create(
    recipe: @recipe, 
    ingredient: @ingredient, 
    amount: params[:recipe_ingredient][:amount] 
) 

    redirect_to recipe_path(@recipe) 
end 

<%= form_for [@recipe_ingredient] do |f|%> 
    <%= f.collection_select :ingredient_id, Ingredient.all, :id, :name %> 

    <%= f.label :amount %> 
    <%= f.number_field :amount, step: :any %> 

    <%= f.submit 'Add Ingredient' %> 
<% end %> 

そして、私の成分のコントローラーで

:P

+1

その優れた '保存を好みます'バージョンを' create'で作成してレコードを作成し、いくつかのパスにリダイレクトすると、いくつかの妥当性検査を行うことができます。例えば'if @ recipe_ingredient.save; redirect_to ...;最後に –

+1

ええ、これはちょうど赤から緑に行くことでした:Dあなたの時間を助けてくれてありがとうございました:D –

+1

あなたはあなた自身の解決策を考え出しました! :) –

関連する問題