从另外两个表创建连接表上的记录

时间:2017-09-08 01:04:16

标签: ruby-on-rails ruby activerecord

我有Recipe模型和Ingredient模型。它们has_many :recipe_ingredients和食谱has_many :ingredients, through: recipe_ingredients和成分has_many :recipes, through: recipe_ingredients以及RecipeIngredient belongs_to食谱和成分。来自recipe#show我有link_to new_recipe_ingredient_path(@recipe)。在那个观点中,我有

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

我的问题是,我ingredients_controllerRecipeIngredient表中创建记录需要什么?我试过铲除了参数。我已经尝试直接在INgredient控制器中创建RecipeIngredient并获取禁用属性错误。我尝试其他的东西,并获得typemismatch。我想知道我是否可以重定向到REcipeINgredient控制器中的create方法并在那里创建它。

2 个答案:

答案 0 :(得分:1)

抱歉,我尝试过这两种方法但没有用。除了

之外,我的新form-for看起来非常相似
<%= 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 %>

在我的成分控制器中

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

我知道这不是最漂亮的但是有效,:P

答案 1 :(得分:0)

根据您的问题&#34;我在ingredients_controller中需要什么才能在RecipeIngredient表中创建记录?&#34;你的代码试图从食谱中创建相反的成分,但我假设你正在尝试实现你的问题,所以这里是:

在您的控制器上修改或添加

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 %>
相关问题