-2

我正在尝试使用 split 类来拆分数组。我不断收到此错误:

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)
4

2 回答 2

6

采用:

params[:listing][:images]

而且它已经是一个Array,不需要拆分。你可以直接做:params[:listing][:images].each

于 2012-12-12T09:09:15.863 回答
4

params[:images]是零,你在params[:listing][:images]我假设之后。

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

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

于 2012-12-12T09:09:19.950 回答