Ruby类'拆分'不起作用

时间:2012-12-12 09:02:20

标签: ruby-on-rails ruby

我正在尝试使用拆分类来拆分数组。我一直收到这个错误:

MethodError (undefined method `split' for nil:NilClass):

这就是我要做的事情:  def create

    @listing.landlord = current_landlord
    if @listing.save
      photo_id_array = params[:images].split(/,/)
      photo_id_array.each do |image|
        @image = Photo.find_by_id("photo.id")
        @image.listing_id = @listing.id
      end
      render :show, :status => 200
    else
      render :status => 403, :json => {:errors => @listing.errors}
    end
  end

我正在运行Rails 3.2.9。可能导致这种情况的任何想法?

编辑:

这是完整的帖子:

Started POST "/listings" for 127.0.0.1 at 2012-12-12 01:04:52 -0800
Processing by ListingsController#create as application/json; charset=utf-8
  Parameters: {"listing"=>{"street_address"=>"123 main st", "city"=>"los angeles", "state"=>"ca", "availability"=>"12 Dec 2012", "price"=>"2000", "period"=>"2", "category"=>"1", "cats"=>"false", "dogs"=>"false", "square_footage"=>"0", "bedrooms"=>"3", "bathrooms"=>"2", "short_description"=>"tree-lined street", "long_description"=>"big yard", "images"=>["70621", "70622", "70620"]}, "auth_token"=>"6489Cn7KeTmejSxaWsws"}
WARNING: Can't verify CSRF token authenticity
  User Load (1.6ms)  SELECT "users".* FROM "users" WHERE "users"."authentication_token" = '6489Cn7KeTmejSxaWsws' LIMIT 1
  Landlord Load (0.6ms)  SELECT "landlords".* FROM "landlords" WHERE "landlords"."authentication_token" = '6489Cn7KeTmejSxaWsws' LIMIT 1
  Role Load (0.5ms)  SELECT "roles".* FROM "roles" WHERE "roles"."name" = 'admin' LIMIT 1
  Role Exists (0.7ms)  SELECT 1 AS one FROM "roles" INNER JOIN "landlords_roles" ON "roles"."id" = "landlords_roles"."role_id" WHERE "landlords_roles"."landlord_id" = 5867 AND "roles"."id" = 1 LIMIT 1
Completed 500 Internal Server Error in 275ms

NoMethodError (undefined method `split' for nil:NilClass):
  app/controllers/listings_controller.rb:8:in `create'


  Rendered /Users/rigelstpierre/.rvm/gems/ruby-1.9.3-p194/gems/actionpack-3.2.9/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.9ms)
  Rendered /Users/rigelstpierre/.rvm/gems/ruby-1.9.3-p194/gems/actionpack-3.2.9/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (2.1ms)
  Rendered /Users/rigelstpierre/.rvm/gems/ruby-1.9.3-p194/gems/actionpack-3.2.9/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (16.9ms)

2 个答案:

答案 0 :(得分:6)

使用:

params[:listing][:images]

它已经是一个阵列,不需要拆分。您可以直接执行:params[:listing][:images].each

答案 1 :(得分:4)

params[:images]是零,你是params[:listing][:images]我假设的。

你的参数的结构如下:"listing"=>{"images"=>["70621", "70622", "70620"]}

另外,你不需要拆分它,它是一个数组。使用以下代码访问数组的每个项目:params[:listing][:images].each do |i|