Rails 4 - 使用has_key时没有方法错误

时间:2014-03-11 22:18:03

标签: ruby-on-rails ruby ruby-on-rails-4

我有这样的行动

def fetch
    @result = LinkThumbnailer.generate(params[:url], strict: false, limit: 1)
    if @result.has_key?('image')
      @result[:thumbnail_url] = @result.image
    elsif @result.has_key?('images')
      @result[:thumbnail_url] = @result.images.first
    else
      @result[:thumbnail_url] = ""
    end
    respond_to do |format|
      format.json { render json: @result }
    end
  end

但我收到此错误

NoMethodError at /bookmarks/new/fetch undefined method `has_key?' for nil:NilClassapp/controllers/bookmarks_controller.rb

但我在IRB中尝试过这样的

2.1.0 :015 > object = LinkThumbnailer.generate('http://dribbble.com/shots/1455760-ID-Card?list=popular&offset=3',strict: false, limit:1)
 => #<LinkThumbnailer::Object description=" Inspired by zee7,AH,Hope you guys like it!" image="https://d13yacurqjgara.cloudfront.net/users/219089/screenshots/1455760/user_thumbnail.png" images=["https://d13yacurqjgara.cloudfront.net/users/219089/screenshots/1455760/user_thumbnail.png"] site_name="Dribbble" title="ID Card" type="article" url="http://dribbble.com/shots/1455760-ID-Card"> 
2.1.0 :016 > object.has_key?('image')
 => true 

has_key在irb中正常工作。谁能告诉我我的代码有什么问题?

1 个答案:

答案 0 :(得分:1)

@result值为零。这就是你收到错误的原因。

查看params [:url]是否等于http://dribbble.com/shots/1455760-ID-Card?list=popular&offset=3

确保LinkThumbnailer.generate(params[:url], strict: false, limit: 1)返回值而不是nil。

def fetch
    puts params[:url] ## Check params[:url] value on console
    @result = LinkThumbnailer.generate(params[:url], strict: false, limit: 1)
    unless @result.nil? ## Check if @result is nil
      if @result.has_key?('image')
        @result[:thumbnail_url] = @result.image
      elsif @result.has_key?('images')
        @result[:thumbnail_url] = @result.images.first
      else
        @result[:thumbnail_url] = ""
      end
      respond_to do |format|
        format.json { render json: @result }
      end
     end
  end