未定义的方法`每个'因为param [“value”]是零

时间:2016-01-26 18:55:14

标签: ruby-on-rails ruby api

我正在轨道上的红宝石中创建一个项目,并通过以下路线创建一个尖叫:

投票反对 费乌瑞 Estou criando um projeto em ruby​​ on rail onde crio um grito com a seguinte rota no postman:

**

controller #create

POST:http://localhost:3000/api/yells
{
    "user_id":"1",
    "title":"caneca",
    "desciption":"beber",
    "yell_type":"oferta",
    "price":"20,00",
    "categories":[{"name":"porcelana"}]
}

然而,正在与我的一位正在做前端的朋友做项目,当他在邮递员的机器上测试时,替换localhost为我的ip,错误:

def create
  #@yell = Yell.new(yell_params.except(:categories))
  @yell = Yell.new({title: params[:title], desciption: params[:desciption], price: params[:price], user_id: params[:user_id], yell_type: params[:yell_type]})

  params[:categories].each do |rel|
    @category = Category.find_by_name(rel[:name])
    if @category
      #only creates the relationship
    else
      @yell.categories.build(name: rel[:name]) #creates the relationship and category
    end
  end

  if @yell.save
    render json: @yell, status: :created, location: api_yell_path(@yell)
  else
    render json: @yell.errors, status: :unprocessable_entity
  end
end

可能在此行中生成错误:

undefined method `each' for nil:NilClass

我想这是因为params [:categories]无效,但它不会来。尤其是因为在我的机器中,它不起作用。

1 个答案:

答案 0 :(得分:3)

您的错误正在告诉您问题的确切位置。当Ruby哈希中的键不包含值时,将返回nil。要帮助解决此问题,您可以替换:

params[:categories]

Array(params[:categories])

帮助each阻止错误。