0

please i need help this is recipe model:

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

and this is Ingredient Model

class Ingredient < ActiveRecord::Base
  has_and_belongs_to_many :recipes,:join_table => "ingredients_recipes"
end

i stuck in the creation action

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

the url comes from the Front End(Angularjs) look like this :

{"recipe":{"name":"hdfndhs","instructions":"lsls,dndcj","ingredients":[{"id":2,"title":"oeuf"}]}}

1 Answers1

0

I guess your problem is you cannot get correct @ingredients.

Please try this code to fetch @ingredients:

@ingredients = Ingredient.where(:id => params[:recipe][:ingredients].map {|ingredient| ingredient[:id]})
Yang
  • 1,915
  • 1
  • 9
  • 15
  • one more thing , i got 'NoMethodError (undefined method `ingredients' for nil:NilClass):' after this, '@recipe.ingredients << @ingredients' – Salem Harrathi Nov 26 '15 at 15:08