【问题标题】:create record on joins table from two other tables从其他两个表创建连接表的记录
【发布时间】:2017-09-08 01:04:16
【问题描述】:

我有一个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_controller 中创建RecipeIngredient 表中的记录吗?我试过铲入参数。我已经尝试直接在 INgredient 控制器中创建 RecipeIngredient 并得到一个禁止属性错误。我尝试其他事情并得到类型不匹配。我想知道是否可以重定向到 REcipeINgredient 控制器中的 create 方法并在那里创建它。

【问题讨论】:

    标签: ruby-on-rails ruby activerecord


    【解决方案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

    【讨论】:

    • 在创建记录并重定向到某个路径时,最好选择save 版本而不是create,因为它允许您进行一些验证检查。例如if @recipe_ingredient.save; redirect_to ...; end
    • 是的,这只是从红色变为绿色 :D 非常感谢您抽出宝贵时间提供帮助 :D
    • 您自己已经找到了解决方案...赞! :)
    【解决方案2】:

    基于您的问题“我需要在我的成分控制器中什么来在 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 %>
    

    【讨论】:

      猜你喜欢
      • 2021-07-26
      • 1970-01-01
      • 1970-01-01
      • 2012-05-12
      • 1970-01-01
      • 1970-01-01
      • 2020-08-18
      • 2011-01-23
      • 2019-04-14
      相关资源
      最近更新 更多