即使find_by返回其他内容,var也设置为nil

时间:2014-05-08 16:48:06

标签: ruby-on-rails ruby

我运行pry-debugger以找出我的控制器无法正常工作的原因。我在第76行设置了一个断点:

    70: def move
    71:   binding.pry
    72:   @moved_slides = []
    73:     @ids.each do |id|
    74:       begin
    75:         @slide = Slide.find_by(id: id)
 => 76:         @moved_slides << @slide.album_id = @new_album_id
    77:       rescue ActiveRecord::RecordNotFound
    78:         flash_message :error, "Cannot move #{id} slide."
    79:       end

并且在第75行有一些我不理解的奇怪内容。由于某些原因@slide设置为nil,即使Slide.find_by(id: id)返回其他内容:

[20] pry(#<SlidesController>)> id
=> "5"
[21] pry(#<SlidesController>)> @slide        
=> nil
[22] pry(#<SlidesController>)> Slide.find_by(id: id)
  CACHE (0.1ms)  SELECT "slides".* FROM "slides" WHERE "slides"."deleted_at" IS NULL AND "slides"."id" = 5 LIMIT 1
=> #<Slide id: 5, album_id: 5, description: "", created_at: "2014-05-08 13:34:47", updated_at: "2014-05-08 13:34:47", photo_file_name: "DSC_2382.JPG", photo_content_type: "image/jpeg", photo_file_size: 1831664, photo_updated_at: "2014-05-08 13:34:47", photo_fingerprint: "c01877ee5d98b1fa456bb174741aef39", deleted_at: nil, photo_processing: true>

btw:我知道如果我想获得find_by!,我应该使用find_by而不是RecordNotFound,但这不是这种情况。

1 个答案:

答案 0 :(得分:0)

您在分配之前检查@slide的值。尝试:

def move
  @moved_slides = []
  @ids.each do |id|
    begin
      @slide = Slide.find_by(id: id)
      binding.pry
      @moved_slides << @slide.album_id = @new_album_id
    rescue ActiveRecord::RecordNotFound
      flash_message :error, "Cannot move #{id} slide."
    end
  end
end

你会发现一切都很好。