- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我知道这是一个很常见的问题,但其他回复都无法帮助我。
我目前正在尝试为我的网站创建测试,但我总是遇到错误
ActionView::Template::Error: undefined method
我的很多方法通常会生成一个 Nill
类。该网站使用登录设备。
这是我要运行的测试。我确保我的装置已加载到测试数据库中
require 'test_helper'
class PagesControllerTest < ActionController::TestCase
include Devise::TestHelpers
include Warden::Test::Helpers
Warden.test_mode!
def setup
sign_in User.first
end
def teardown
Warden.test_reset!
end
test "should get index" do
get :index
assert_response :success
end
test "should get voting" do
get :voting
assert_response :success
end
end
这些是尝试运行测试时的错误消息
Minitest::UnexpectedError: ActionView::Template::Error: undefined method `strip' for nil:NilClass
config/initializers/addChallenges.rb:22:in `findChallenges'
app/views/pages/index.html.erb:11:in `_app_views_pages_index_html_erb__190802989_69818040'
test/controllers/pages_controller_test.rb:18:in `block in <class:PagesControllerTest>'
config/initializers/addChallenges.rb:22:in `findChallenges'
app/views/pages/index.html.erb:11:in `_app_views_pages_index_html_erb__190802989_69818040'
test/controllers/pages_controller_test.rb:18:in `block in <class:PagesControllerTest>'
Minitest::UnexpectedError: ActionView::Template::Error: undefined method `strip' for nil:NilClass
config/initializers/addIdeas.rb:25:in `findIdeas'
app/views/pages/voting.html.erb:6:in `_app_views_pages_voting_html_erb___557022735_70668940'
test/controllers/pages_controller_test.rb:24:in `block in <class:PagesControllerTest>'
config/initializers/addIdeas.rb:25:in `findIdeas'
app/views/pages/voting.html.erb:6:in `_app_views_pages_voting_html_erb___557022735_70668940'
test/controllers/pages_controller_test.rb:24:in `block in <class:PagesControllerTest>'
Finished in 0.31402s
2 tests, 0 assertions, 0 failures, 2 errors, 0 skips
Process finished with exit code 0
在这种情况下跟踪错误时,此行显示为有问题 resp = http.get(url.path, headers)
这是我的完整 addIdeas 代码,但 addChallenges 代码非常相似。
class AddIdeas
#a method that will find all the challenge ideas for a user and then store them in our databse
def self.findIdeas(email,challengeId)
require "net/http"
require "uri"
require 'json'
require 'active_record'
p= People.find_by_email(email)
uri_string = 'http://sideways6.com/api/V1/Idea/Challenge/'
uri_string << challengeId.to_s
#make the http request with the headers
url = URI.parse(uri_string)
http = Net::HTTP.new(url.host, url.port)
headers = {
'Authorization' => p.basic,
'UserId' => p.userId,
'AuthorizationToken' => p.auth_tok
}
#retrieve a get response
resp = http.get(url.path, headers)
#if response is okay parse the challenge ids and add them to the person table for that user
if resp.code.to_s == '200'
if resp.body.to_s != 'null'
puts parsed = JSON.parse(resp.body)
ids = ""
parsed.each do |element|
addIdeas(element, challengeId)
ids << "#{element['IdeaId']},"
end
c = Challenges.find_by_challengeId(challengeId)
c.ideaIds = ids
c.save
end
end
end
def self.addIdeas(element, challengeId)
i = Ideas.find_by_ideaId(element['IdeaId'])
if i == nil
i = Ideas.create(:ideaId => element['IdeaId'], :title => element['Title'], :description => element['Description'], :challengeIds => challengeId, :score=>1000, :faceOff => 0, :wins =>0)
end
if i != nil
i.ideaId = (element['IdeaId'])
i.title = (element['Title'])
i.description = (element['Description'])
i.challengeIds = challengeId
i.save
end
end
def self.findAllIdeas(email)
p = People.find_by_email(email)
ids = p.challenges
splitted = ids.split(",")
counter = splitted.length
i =0
while i < counter.to_i do
findIdeas(email, splitted[i])
i += 1
end
end
end
添加挑战文件
class AddChallenges
#a method that will find all the challenge ideas for a user and then store them in our databse
def self.findChallenges(email)
require "net/http"
require "uri"
require 'json'
require 'active_record'
p= People.find_by_email(email)
#make the http request with the headers
url = URI.parse('http://sideways6.com/api/V1/Challenge/All')
http = Net::HTTP.new(url.host, url.port)
headers = {
'Authorization' => p.basic,
'UserId' => p.userId,
'AuthorizationToken' => p.auth_tok
}
#retrieve a get response
resp = http.get(url.path, headers)
#if response is okay parse the challenge ids and add them to the person table for that user
if resp.code.to_s == '200'
puts parsed = JSON.parse(resp.body)
ids = ""
parsed.each do |element|
addChallenges(element)
ids << "#{element['ChallengeId']},"
end
p = People.find_by_email(email)
p.challenges = ids
p.save
end
end
def self.addChallenges(element)
c = Challenges.find_by_challengeId(element['ChallengeId'])
if c == nil
c = Challenges.create(:challengeId => element['ChallengeId'], :title => element['Title'], :description => element['Description'])
end
if c != nil
c.challengeId = (element['ChallengeId'])
c.title = (element['Title'])
c.description = (element['Description'])
c.save
end
end
def self.retrieveChallengeObject(challengeId)
c = Challenges.find_by_challengeId(challengeId)
end
end
请求的我的页面 Controller
class PagesController <ApplicationController
def home
@current_nav_identifier = :home
end
end
索引页
<script type="text/javascript">window._token = '<%= form_authenticity_token %>';</script>
<body>
<noscript>
<div class='warning-page-cover'>
<div class='alert alert-info'>
<h2>Sorry about that, it appears that you are using a web browser without JavaScript which prevents us offering you a rich online experience.</h2>
<p>Please enable JavaScript or use a different web browser, or alternatively contact the CiCS Helpdesk for assistance.</p>
</div>
</div>
</noscript>
<%AddChallenges.findChallenges(current_user.email)%>
<%AddIdeas.findAllIdeas(current_user.email)%>
<div id='wrap'>
<nav class='navbar navbar-default navbar-fixed-top' id='main-nav'>
<div class='container-fluid'>
<div class='navbar-header'>
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class='icon-bar'></span>
<span class='icon-bar'></span>
<span class='icon-bar'></span>
</button>
<a href="<%= url_for(:controller=> 'pages', :action => 'index')%>">
<%= image_tag('/logo.png', :alt => "Sideways 6 Logo", size:"203x50") %>
</a>
</div>
<div class='collapse navbar-collapse' id="bs-example-navbar-collapse-1">
<ul class='nav navbar-nav'>
</ul>
<% if true # user_signed_in? %>
<ul class="nav navbar-nav navbar-right">
<li><%= link_to fa_icon('index', text: 'Refresh Challenges'), root_path , method: :get %></li>
<li class="dropdown">
<%= link_to '#', data: { toggle: :dropdown }, class: 'dropdown-toggle' do %>
<span class="glyphicon glyphicon-user" aria-hidden="true"></span>
<% p = People.find_by_email(current_user.email)%>
<% fName = p.firstName %>
<% if fName != nil %>
<%= fa_icon('user', text: fName )%>
<%end%>
<% if fName == nil %>
<%= fa_icon('user', text: current_user.email) %>
<%end%>
<b class="caret"></b>
<% end %>
<ul class="dropdown-menu">
<li>
<%# log out path is usually: destroy_user_session_path %>
<%= link_to fa_icon('index', text: Score.retrieveUserScore(current_user.email)), root_path , method: :get %>
<%= link_to fa_icon('challenges', text:'All Challenges'), challenges_path, method: :get, title: "See all Challenges" %>
<%= link_to fa_icon('sign-out', text: 'Log out'), destroy_user_session_path, method: :get, title: "Log out of the system" %>
</li>
</ul>
</li>
</ul>
<% end %>
</div>
</div>
</nav>
<div id="main">
<h1>Select A Challenge To Vote On</h1>
<% p = People.find_by_email(current_user.email) %>
<% ids = p.challenges %>
<% splitted = ids.split(",") %>
<% counter = splitted.length %>
<p class="lead">Please Select One</p>
<% i =0 %>
<% while i < counter.to_i do %>
<div class="row">
<div class="col-xs-12 col-md-6">
<% c = AddChallenges.retrieveChallengeObject(splitted[i]) %>
<% if Vote.canVote(splitted[i]) == true %>
<a href="<%= url_for(:controller=> 'pages', :action => 'voting')%>?challengeId=<%=(splitted[i])%>" class="challenge-select" data-challengeid="<%=(splitted[i])%>">
<div class="well clickable">
<h4><%= c.title %></h4>
<p class="text-center"> <%= c.description %> </p>
</div>
</a>
<% end %>
</div>
<% i+=1 %>
<% if i != counter %>
<div class="col-xs-12 col-md-6">
<% c = AddChallenges.retrieveChallengeObject(splitted[i]) %>
<% if Vote.canVote(splitted[i]) == true %>
<a href="<%= url_for(:controller=> 'pages', :action => 'voting')%>?challengeId=<%=(splitted[i])%>" class="challenge-select" data-challengeid="<%=(splitted[i])%>">
<div class="well clickable">
<h4><%= c.title %></h4>
<p class="text-center"><%= c.description %></p>
</div>
</a>
<% end %>
</div>
<%end%>
</div>
<% i+=1 %>
<%end%>
<%= yield %>
</div>
</div>
和投票html
<script type="text/javascript">window._token = '<%= form_authenticity_token %>';</script>
<% require 'digest/sha1'
salt = '%+5)_' %>
<% AddIdeas.findIdeas(current_user.email,params[:challengeId]) %>
<% if params[:winner] != nil
concat = "#{salt}#{params[:challengeId]}#{params[:winner]}#{params[:loser]}#{salt}"
hash = Digest::SHA1.hexdigest(concat)
if hash == params[:hash]
Score.updateScore(params[:winner],params[:loser])
Score.userScore(current_user.email)
end
end %>
<div id='wrap'>
<nav class='navbar navbar-default navbar-fixed-top' id='main-nav'>
<div class='container-fluid'>
<div class='navbar-header'>
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class='icon-bar'></span>
<span class='icon-bar'></span>
<span class='icon-bar'></span>
</button>
<a href="<%= url_for(:controller=> 'pages', :action => 'index')%>">
<%= image_tag('/logo.png', :alt => "Sideways 6 Logo", size:"203x50") %>
</a>
</div>
<div class='collapse navbar-collapse' id="bs-example-navbar-collapse-1">
<ul class='nav navbar-nav'>
</ul>
<% if true # user_signed_in? %>
<ul class="nav navbar-nav navbar-right">
<li><%= link_to fa_icon('index', text: 'Change Challenge'), root_path , method: :get %></li>
<li class="dropdown">
<%= link_to '#', data: { toggle: :dropdown }, class: 'dropdown-toggle' do %>
<span class="glyphicon glyphicon-user" aria-hidden="true"></span>
<% p = People.find_by_email(current_user.email)%>
<% fName = p.firstName %>
<% if fName != nil %>
<%= fa_icon('user', text: fName )%>
<%end%>
<% if fName == nil %>
<%= fa_icon('user', text: current_user.email) %>
<%end%>
<b class="caret"></b>
<% end %>
<ul class="dropdown-menu">
<li>
<%# log out path is usually: destroy_user_session_path %>
<%= link_to fa_icon('index', text: Score.retrieveUserScore(current_user.email)), root_path , method: :get %>
<%= link_to fa_icon('challenges', text:'All Challenges'), challenges_path, method: :get, title: "See all Challenges" %>
<%= link_to fa_icon('sign-out', text: 'Log out'), destroy_user_session_path, method: :get, title: "Log out of the system" %>
</li>
</ul>
</li>
</ul>
<% end %>
</div>
</div>
</nav>
<div id="main">
<% c = Challenges.find_by_challengeId(params[:challengeId]) %>
<% ids = c.try(:ideaIds) %>
<% splitted = ids.try(:split, ",") %>
<% shuffle = splitted.try(:shuffle) %>
<% firstIdea = shuffle.try(:first) %>
<% lastIdea = shuffle.try(:last) %>
<% f = Ideas.find_by_ideaId(firstIdea)%>
<% l = Ideas.find_by_ideaId(lastIdea)%>
<h1><%=c.try(:title)%></h1>
<p class="lead">Which best solves the challenge?</p>
<div class="row">
<div class="col-xs-12 col-md-6">
<% challengeId = params[:challengeId]
winner = f.try(:ideaId)
loser = l.try(:ideaId)
concat = "#{salt}#{challengeId}#{winner}#{loser}#{salt}"
hash = Digest::SHA1.hexdigest(concat) %>
<a href="<%= url_for(:controller=> 'pages', :action => 'voting')%>?challengeId=<%=(params[:challengeId])%>&winner=<%=(f.try(:ideaId))%>&loser=<%=(l.try(:ideaId))%>&hash=<%=(hash)%>" class="idea-vote" data-challengeid="<%=(params[:challengeId])%>" data-winner="<%=(f.try(:ideaId))%>" data-loser="<%=(l.try(:ideaId))%>" data-hash="<%=(hash)%>">
<div class="well clickable">
<h4><%= f.try(:title) %></h4>
<p class="text-center"><%= f.try(:description)%></p>
</div>
</a>
</div>
<div class="col-xs-12 col-md-6">
<% challengeId = params[:challengeId]
winner = l.try(:ideaId)
loser = f.try(:ideaId)
concat = "#{salt}#{challengeId}#{winner}#{loser}#{salt}"
hash = Digest::SHA1.hexdigest(concat) %>
<a href="<%= url_for(:controller=> 'pages', :action => 'voting')%>?challengeId=<%=(params[:challengeId])%>&winner=<%=(l.try(:ideaId))%>&loser=<%=(f.try(:ideaId))%>&hash=<%=(hash)%>" class="idea-vote" data-challengeid="<%=(params[:challengeId])%>" data-winner="<%=(l.try(:ideaId))%>" data-loser="<%=(f.try(:ideaId))%>" data-hash="<%=(hash)%>">
<div class="well clickable">
<h4><%=l.try(:title)%></h4>
<p class="text-center"><%=l.try(:description)%></p>
</div>
</a>
</div>
</div>
<a href="<%= url_for(:controller=> 'pages', :action => 'voting')%>?challengeId=<%=(params[:challengeId])%>" class="btn btn-default btn-sm">Skip <span class="glyphicon glyphicon-chevron-right"></span></a>
<%= yield %>
</div>
</div>
我曾尝试使用 try()
修改方法,有时似乎可以解决问题,但之后 try()
会导致网站本身出现问题。有时,错误消息会将我重定向到使用方法的 html View 文件本身。
编辑:好的,在修复标题后,我现在得到了
Minitest::UnexpectedError: ActionView::Template::Error: undefined method `split' for nil:NilClass
config/initializers/addIdeas.rb:61:in `findAllIdeas'
app/views/pages/index.html.erb:12:in `_app_views_pages_index_html_erb__1448445017_66568380'
test/controllers/pages_controller_test.rb:17:in `block in <class:PagesControllerTest>'
config/initializers/addIdeas.rb:61:in `findAllIdeas'
app/views/pages/index.html.erb:12:in `_app_views_pages_index_html_erb__1448445017_66568380'
test/controllers/pages_controller_test.rb:17:in `block in <class:PagesControllerTest>'
Minitest::UnexpectedError: ActionView::Template::Error: undefined method `score' for #<People:0x000000085d17b0>
config/initializers/score.rb:50:in `retrieveUserScore'
app/views/pages/voting.html.erb:56:in `_app_views_pages_voting_html_erb___944539514_69504160'
test/controllers/pages_controller_test.rb:23:in `block in <class:PagesControllerTest>'
config/initializers/score.rb:50:in `retrieveUserScore'
app/views/pages/voting.html.erb:56:in `_app_views_pages_voting_html_erb___944539514_69504160'
test/controllers/pages_controller_test.rb:23:in `block in <class:PagesControllerTest>'
Finished in 0.53103s
2 tests, 0 assertions, 0 failures, 2 errors, 0 skips
Process finished with exit code 0
score.rb 文件
class Score
def self.updateScore(winner, loser)
Math.exp(1)
w = Ideas.find_by_ideaId(winner)
l = Ideas.find_by_ideaId(loser)
# updatewinner
# games W played = get number of times the winner has matched up against other ideas
# winner new score = winner score + (1000/games W played) (1+ 1/(1 + Math.exp(loser score - winner score)))
w.faceOff += 1
w.save
lScore = l.score
wScore = w.score
wGames = w.faceOff
newWScore = wScore + (500/wGames)*(1-(1/(1 + Math.exp(lScore - wScore))))
l.faceOff += 1
l.save
lGames = l.faceOff
newLScore = lScore + (500/lGames)*(-1/(1+ Math.exp(wScore - lScore)))
puts "New Winner Score "
puts newWScore
w.score = newWScore
w.save
puts "New Loser Score "
puts newLScore
l.score = newLScore
l.save
puts newWScore
# updateloser
# games L played = get number of times the loser has matched up against other ideas
# loser new score = loser score + (1000/games L played) (1+ 1/(Math.exp(winner score - loser score)))
end
def self.userScore(email)
p = People.find_by_email(email)
score = p.score
newScore = score + 1
p.score = newScore
p.save
end
def self.retrieveUserScore(email)
p = People.find_by_email(email)
score = 'Score: ' << p.score.to_s
end
end
最佳答案
好的,我做了一些测试:
您的错误是您的 header
之一参数将从您的数据库返回为 nil
我可以通过设置来复制你的错误
headers = {
'Authorization' => nil,
'UserId' => nil,
'AuthorizationToken' => nil
}
正在运行http.get(url.path, headers)
要避免异常并让 API 返回错误,您可以做的是测试 nil 并将其替换为空字符串 ""
例如:'Authorization' => p.basic || ""
编辑:对于您上面的编辑...
有两个错误:
ActionView::Template::Error: undefined method 'split' for nil:NilClass
发生这种情况是因为:
ids = p.challenges
splitted = ids.split(",")
如果 ids 为 nil,则不能调用 split
在上面。此时您需要添加一张支票并返回。
ActionView::Template::Error: undefined method 'score' for #<People:0x000000085d17b0>
你的 People
模型没有 score
方法
关于ruby-on-rails - Rails ActionView::Template::Error:Nill 类的未定义方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30109856/
reqwest v0.9 将 serde v1.0 作为依赖项,因此实现 converting serde_json errors into reqwest error . 在我的代码中,我使用 se
我有这个代码: let file = FileStorage { // ... }; file.write("Test", bytes.as_ref()) .map_err(|e| Mu
我只是尝试用angular-cli创建一个新项目,然后运行服务器,但是它停止并显示一条有趣的消息:Error: No errors。 我以这种方式更新了(希望有帮助):npm uninstall -g
我从我的 javascript 发送交易 Metamask 打开传输对话框 我确定 i get an error message in metamask (inpage.js:1 MetaMask -
这个问题在这里已经有了答案: How do you define custom `Error` types in Rust? (3 个答案) How to get a reference to a
我想知道两者之间有什么大的区别 if let error = error{} vs if error != nil?或者只是人们的不同之处,比如他们如何用代码表达自己? 例如,如果我使用这段代码: u
当我尝试发送超过 50KB 的图像时,我在 Blazor 服务器应用程序上收到以下错误消息 Error: Connection disconnected with error 'Error: Serv
我有一个error-page指令,它将所有异常重定向到错误显示页面 我的web.xml: [...] java.lang.Exception /vi
我有这样的对象: address: { "phone" : 888, "value" : 12 } 在 WHERE 中我需要通过 address.value 查找对象,但是在 SQL 中有函数
每次我尝试编译我的代码时,我都会遇到大量错误。这不是我的代码的问题,因为它在另一台计算机上工作得很好。我尝试重新安装和修复,但这没有帮助。这是整个错误消息: 1>------ Build starte
在我的代码的类部分,如果我写一个错误,则在不应该的情况下,将有几行报告为错误。我将'| error'放在可以从错误中恢复的良好/安全位置,但是我认为它没有使用它。也许它试图在某个地方恢复中间表情? 有
我遇到了 csv 输入文件整体读取故障的问题,我可以通过在 read_csv 函数中添加 "error_bad_lines=False" 来删除这些问题来解决这个问题。 但是我需要报告这些造成问题的文
在 Spring 中,验证后我们在 controller 中得到一个 BindingResult 对象。 很简单,如果我收到验证错误,我想重新显示我的表单,并在每个受影响的字段上方显示错误消息。 因此
我不知道出了什么问题,因为我用 Java 编程了大约一年,从来没有遇到过这个错误。在一分钟前在 Eclipse 中编译和运行工作,现在我得到这个错误: #A fatal error has been
SELECT to_char(messages. TIME, 'YYYY/MM/DD') AS FullDate, to_char(messages. TIME, 'MM/DD
我收到这些错误: AnonymousPath\Anonymized.vb : error BC30037: Character is not valid. AnonymousPath\Anonymiz
我刚刚安装了 gridengine 并在执行 qstat 时出现错误: error: commlib error: got select error (Connection refused) erro
嗨,我正在学习 PHP,我从 CRUD 系统开始,我在 Windows 上安装了 WAMP 服务器,当我运行它时,我收到以下错误消息。 SCREAM: Error suppression ignore
我刚刚开始一个新项目,我正在学习核心数据教程,可以找到:https://www.youtube.com/watch?v=zZJpsszfTHM 我似乎无法弄清楚为什么会抛出此错误。我有一个名为“Exp
当我使用 Jenkins 运行新构建时,出现以下错误: "FilePathY\XXX.cpp : fatal error C1853: 'FilePathZ\XXX.pch' precompiled
我是一名优秀的程序员,十分优秀!