创建动作,habtm 关系
create action,habtm relation
我需要帮助
这是配方模型:
class Recipe < ActiveRecord::Base
mount_uploader :cover, AvatarUploader
belongs_to :user
has_and_belongs_to_many :ingredients,:join_table =>
"ingredients_recipes"
accepts_nested_attributes_for :ingredients
end
这是成分模型
class Ingredient < ActiveRecord::Base
has_and_belongs_to_many :recipes,:join_table => "ingredients_recipes"
end
我卡在创作动作中了
def create
#@ingredient = Ingredient.find(params[:ingredients][:id])
@ingredients = Ingredient.where(:id => params[:recipe][:ingredients])
@recipe = Recipe.new(params.require(:recipe).permit(:name,:instructions,:cover,:user_id,:ingredients))
#params[:ingredients].each_pair do |k,v|
@recipe.ingredients << @ingredients
#end
#@recipe = current_user.recipes.new(params.require(:recipe).permit(:name,:instructions,:cover,:user_id, ingredients: [:id, :title] ))
@recipe.cover = params[:cover]
#@recipe.user_id = current_user.id
@recipe.save
render 'show', status: 201
end
url 来自前端 (Angularjs) 看起来像这样:
{"recipe":{"name":"hdfndhs","instructions":"lsls,dndcj","ingredients":[{"id":2,"title":"oeuf"}]}}
我猜你的问题是你无法正确回答 @ingredients
。
请尝试使用此代码获取 @ingredients
:
@ingredients = Ingredient.where(:id => params[:recipe][:ingredients].map {|ingredient| ingredient[:id]})
我需要帮助 这是配方模型:
class Recipe < ActiveRecord::Base
mount_uploader :cover, AvatarUploader
belongs_to :user
has_and_belongs_to_many :ingredients,:join_table =>
"ingredients_recipes"
accepts_nested_attributes_for :ingredients
end
这是成分模型
class Ingredient < ActiveRecord::Base
has_and_belongs_to_many :recipes,:join_table => "ingredients_recipes"
end
我卡在创作动作中了
def create
#@ingredient = Ingredient.find(params[:ingredients][:id])
@ingredients = Ingredient.where(:id => params[:recipe][:ingredients])
@recipe = Recipe.new(params.require(:recipe).permit(:name,:instructions,:cover,:user_id,:ingredients))
#params[:ingredients].each_pair do |k,v|
@recipe.ingredients << @ingredients
#end
#@recipe = current_user.recipes.new(params.require(:recipe).permit(:name,:instructions,:cover,:user_id, ingredients: [:id, :title] ))
@recipe.cover = params[:cover]
#@recipe.user_id = current_user.id
@recipe.save
render 'show', status: 201
end
url 来自前端 (Angularjs) 看起来像这样:
{"recipe":{"name":"hdfndhs","instructions":"lsls,dndcj","ingredients":[{"id":2,"title":"oeuf"}]}}
我猜你的问题是你无法正确回答 @ingredients
。
请尝试使用此代码获取 @ingredients
:
@ingredients = Ingredient.where(:id => params[:recipe][:ingredients].map {|ingredient| ingredient[:id]})