Ruby on rails Rails 4-使用has\u键时没有方法错误
我有这样的动作Ruby on rails Rails 4-使用has\u键时没有方法错误,ruby-on-rails,ruby,ruby-on-rails-4,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] = @resul
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
2.1.0:015>object=LinkThumbnailer.generate('http://dribbble.com/shots/1455760-ID-Card?list=popular&offset=3,严格:错误,限制:1)
=> #
2.1.0:016>对象。是否有_键?(“图像”)
=>正确
has_key
在irb中工作正常。有人能告诉我我的代码有什么问题吗?@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
是的。。你说得对@结果的值为零。谢谢你的时间:)很乐意帮忙。请在超时结束后接受答案:)看起来我需要再等5分钟才能接受您的答案。我会的。别担心。当心