【发布时间】:2018-03-07 14:31:21
【问题描述】:
所以我正在开发一个食谱书导轨应用程序。用户可以创建配方、查看配方和更新配方。但是,当我更新特定成分的数量(即 Pasta "2 Cups" )时,它会将包含意大利面的所有其他食谱更改为该新数量(“2 Cups”)。我可以在我的 rails 控制台和服务器中看到它可以识别更改和更新,但是当我显示视图时,它看起来好像显示了成分的第一个实例,而不是我刚刚更新的那个。我有一种强烈的感觉,这是我在配料中的数量方法的错误,但我不知道如何解决它。
配方模型
class Recipe < ApplicationRecord
belongs_to :user, required: false
has_many :recipe_ingredients
has_many :ingredients, through: :recipe_ingredients
validates :name, presence: true
validates :instructions, presence: true
validates :cooktime, presence: true
def self.alphabetize
self.order(name: :asc)
end
def ingredients_attributes=(ingredients_attributes)
self.ingredients = []
ingredients_attributes.values.each do |ingredients_attribute|
if !ingredients_attribute[:name].empty?
new_ingredient = Ingredient.find_or_create_by(name:
ingredients_attribute[:name])
self.recipe_ingredients.build(ingredient_id: new_ingredient.id,
quantity: ingredients_attribute[:quantity])
end
end
end
end
配料模型
class Ingredient < ApplicationRecord
has_many :recipe_ingredients
has_many :recipes, through: :recipe_ingredients
def self.alphabetize
self.order(name: :asc)
end
def quantity
recipe_ingredient = RecipeIngredient.find_by(recipe_id:
self.recipes.first.id, ingredient_id: self.id)
recipe_ingredient.quantity
end
end
食谱展示、编辑和更新操作:
def show
@recipe = Recipe.find(params[:id])
@ingredients = @recipe.ingredients.alphabetize
end
def edit
@recipe = Recipe.find(params[:id])
end
def update
@recipe = Recipe.find(params[:id])
if @recipe.user = current_user
if @recipe.update(recipe_params)
redirect_to @recipe
else
render :edit
end
end
end
查看/食谱/展示(成分 - 数量)列表:
<% @recipe.ingredients.each do |ingredient|%>
<li><%=ingredient.name %> - <%=ingredient.quantity%></li>
<%end%>
【问题讨论】:
标签: ruby-on-rails ruby database activerecord