создать действие, отношение habtm

0

пожалуйста, мне нужна помощь, это модель рецепта:

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-адрес от Front End (Angularjs) выглядит так:

{"recipe":{"name":"hdfndhs","instructions":"lsls,dndcj","ingredients":[{"id":2,"title":"oeuf"}]}}
Теги:
has-and-belongs-to-many

1 ответ

0
Лучший ответ

Я думаю, ваша проблема в том, что вы не можете получить правильные @ingredients.

Попробуйте этот код, чтобы получить @ingredients:

@ingredients = Ingredient.where(:id => params[:recipe][:ingredients].map {|ingredient| ingredient[:id]})
  • 0
    еще одна вещь, я получил «NoMethodError (неопределенный метод« ингридиенты »для nil: NilClass):« после этого », @recipe.ingredients << @ingredients '
  • 0
    Большое спасибо !! это решено !!

Ещё вопросы

Сообщество Overcoder
Наверх
Меню