gpt4 book ai didi

ruby-on-rails - 如何使用 Rails form_for 获取同一模型的多条记录

转载 作者:行者123 更新时间:2023-12-04 18:01:21 25 4
gpt4 key购买 nike

我正在尝试构建一个基本的食谱应用程序,但在允许用户为一个食谱输入多种成分时遇到了问题。成分的允许参数数组最终为空。所以我想我的问题是 - 我如何允许一系列成分?

我的 Controller :

class RecipesController < ApplicationController

def new
@recipe = Recipe.new
@ingredient = Ingredient.new
end

def create
safe_params = params.require(:recipe).permit(:title, :instruction, :category_id)
ingredient_params = params.require(:recipe).permit(:ingredient => [])
@recipe = Recipe.new(safe_params)
@recipe.save
ingredient_params.each do |i|
@recipe.ingredients << Ingredient.find_or_create_by(name: i[:ingredient][:name])
end
render body: YAML::dump(ingredient_params)
#redirect_to index_path(id: @recipe.id)
end

end

表格:

<%= form_for(@recipe, :url => create_path) do |f| %>
<%= f.label :category %>
<%= f.select :category_id, options_for_select(Category.all.map{|c|[c.title, c.id]}) %>

<%= f.label :title %>
<%= f.text_field :title%>

<%= f.label :instruction %>
<%= f.text_area(:instruction, size: "50x10") %>

<%= f.fields_for "ingredients[]", @ingredient do |i| %>
<%= i.label :name %>
<%= i.text_field :name %>
<%= i.text_field :name %>
<%= i.text_field :name %>
<% end %>

<%= f.submit "Submit" %>
<% end %>

模型:

class Recipe < ActiveRecord::Base
has_and_belongs_to_many :ingredients
accepts_nested_attributes_for :ingredients
belongs_to :category
end

class Category < ActiveRecord::Base
has_many :recipes
end

class Ingredient < ActiveRecord::Base
has_and_belongs_to_many :recipes
end

最佳答案

这里有几个问题,我只提供我会做的:

#app/controllers/recipes_controller.rb
class RecipesController < ApplicationController

def new
@recipe = Recipe.new
@recipe.ingredients.new
end

def create
@recipe = Recipe.new safe_params
@recipe.save
end

private

def safe_params
params.require(:recipe).permit(:title, :instruction, :category_id, ingredients_attributes: [:name])
end

end

#app/views/recipes/new.html.erb
<%= form_for @recipe do |f| %>
<%= f.label :category %>
<%= f.collection_select :category_id, Category.all, :id, :name %>

<%= f.label :title %>
<%= f.text_field :title%>

<%= f.label :instruction %>
<%= f.text_area(:instruction, size: "50x10") %>

<%= f.fields_for :ingredients do |i| %>
<%= i.label :name %>
<%= i.text_field :name %>
<% end %>

<%= f.submit "Submit" %>
<% end %>

如果您想拥有多个ingredients 字段,则必须在 Controller 中构建多个对象:

def new
@recipe = Recipe.new
3.times do
@recipe.ingedients.build
end
end

其他一切看起来都会很好。

--

另外,如果您想填充has_and_belongs_to_many 关系,您只需传递[relationship]_ids 参数即可:

<%= form_for @recipe do |f| %>
<%= f.collection_select :ingredient_ids, Ingredient.all, :id, :name %>
<%= f.submit %>
<% end %>

这仅适用于当前存在的成分。如果你想创造新的成分,上面的方法就可以了。

关于ruby-on-rails - 如何使用 Rails form_for 获取同一模型的多条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34891698/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com