【问题标题】:Create method with join table - has and belongs to many使用连接表创建方法 - 拥有并属于许多
【发布时间】:2019-03-16 00:10:43
【问题描述】:

好的,我有一个问题。我尝试将一些成分 ID 添加到我的数据库中,但我不知道该怎么做。

在我的控制器中我有方法创建

def create
  @drink = Drink.new(drink_params)
  @ingredient = Ingredient.find(params[:id])
  if @drink.save
    @drink.ingredients << @ingredient
    redirect_to drinks_path
  else
    render 'new'
  end
end

然后我有错误:找不到没有 ID 的成分。

但是当我将 @ingredient = Ingredient.find(params[:id]) 更改为 @ingredient = Ingredient.all 时,一切正常。但我不想把我所有的配料都加进去,只是其中的一些。

任何人都可以帮助我并逐步解释它吗?我将不胜感激。

【问题讨论】:

标签: ruby-on-rails ruby jointable


【解决方案1】:

要节省配料和饮料,您需要将accepts_nested_attributes_for 添加到您的Drink 模型:

# app/models/drink.rb

class Drink < ActiveRecord::Base
  accepts_nested_attributes_for :ingredients
  ...
end

然后在控制器的drink_params 方法中添加ingredients_attributes 作为允许的参数属性。成分的字段集取决于您的认识。例如,如果您希望用户可以在其中键入成分名称的 UI,并且仅当数据库中还没有此类成分时才创建该成分的新记录,那么您需要查找 ingrediends 表和将id 添加到ingredients_attributes

# app/controllers/drinks_controller.rb

class DrinksController < ApplicationController
  def create
    @drink = Drink.new(drink_params)
    if @drink.save
      redirect_to drinks_path
    else
      render 'new'
    end
  end

  private

  def drink_params
    params.require(:drink).permit(:name, ingredients_attributes: [:name]).tap do |p|
      p[:ingredients_attributes].each do |i|
        ingredient = Ingredient.find_by(name: i[:name])
        i[:id] = ingredient.id if ingredient
      end
    end
  end
end

【讨论】:

    猜你喜欢
    • 2017-11-05
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多