你可以@ingredient = @recipe.ingredients.first
(如果它真的是唯一的,不知道你怎么能确定这一点。)
假设您已经选择了成分,就像在变量中一样,您可以像设置任何其他 ActiveRecord 对象一样设置它们。
@ingredient = @recipe.ingredients.first
@ingredient.amount = 15 #or @ingredient.amount = params[:amount] (if you get the new value from POST)
@ingredient.unit = "Ounces"
@ingredient.save
如果您只想检索食谱的每种成分的属性并对其进行处理,例如在视图中的某些 html 标记中显示它们,您可以尝试这样做。
@ingredients = @recipe.ingredients
@ingredients.each do |ingr|
info = %w[amount, brand, id, recipe_id , unit].map do |attr|
ingr.send(attr)
end
在每个内部循环的末尾,数组“信息”将是一种成分的所有属性。(假设您将它们包含在信息数组中)
这是您可能用于存储关联的表的示例,它应该与 rails:through => :recipe_ingedient
方法一起使用:
CREATE TABLE `recipe_ingredient` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`recipe_id` int(11) NOT NULL,
`ingedient_id` int(11) NOT NULL,
`created_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=59 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci$$