我正在尝试实现的非常简单的过程。在主页或登录页面上,我想为电子邮件列表捕获电子邮件。如果电子邮件通过验证,它会被保存,太好了!没有错误时一切正常。
当出现仅输入“a”字符等错误时,如下面的日志所示。甚至只是一个空字符串,我不断得到相同的结果TypeError
(无法将 nil 转换为字符串)
这是日志:
Started GET "/" for 127.0.0.1 at 2013-06-13 13:48:56 -0400
Connecting to database specified by database.yml
Processing by HighVoltage::PagesController#show as HTML
Parameters: {"id"=>"home"}
Rendered shared/_error_messages.html.erb (0.4ms)
Rendered layouts/_visitor_form.html.erb (7.9ms)
Rendered pages/home.html.erb within layouts/application (13.1ms)
Completed 200 OK in 82ms (Views: 39.6ms | ActiveRecord: 1.8ms)
[2013-06-13 13:48:57] WARN Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true
Started POST "/visitors" for 127.0.0.1 at 2013-06-13 13:48:59 -0400
Processing by VisitorsController#create as HTML
Parameters: {"utf8"=>"✓",authenticity_token"=>"esTPNzNtkmNPTe7Jh+E2aDHNrgocU5Z8g49Nj0QiOhQ=", "visitor"=>{"email"=>""}, "commit"=>"Add to newsletter list"}
(0.1ms) begin transaction
Visitor Exists (0.2ms) SELECT 1 AS one FROM "visitors" WHERE LOWER("visitors"."email") = LOWER('') LIMIT 1
(0.1ms) rollback transaction
Completed 500 Internal Server Error in 39ms
TypeError (can't convert nil into String):
app/controllers/visitors_controller.rb:12:in `create'
这是visitors_controller.rb
def create
@visitor = Visitor.new(params[:visitor])
if @visitor.save
flash[:success] = "Your email has been added!"
redirect_to '/'
else
render '/'
end
end
我也试过
@visitor = Visitor.new(:visitor => params[:visitor][:email])
以及其他一些没有成功的序列。
如何获得不成功的保存以优雅地显示验证错误并允许用户重新提交。
这是布局:
<%= form_for Visitor.new do |f| %>
<%= render 'shared/error_messages' %>
<%= f.label :email %>
<%= f.text_field :email %>
<%= f.submit "Add to newsletter list", class: "btn btn-large btn-primary" %>
<% end %>
也许高压宝石把我搞砸了。我没有足够的经验知道。
更新:
rake routes
visitors POST /visitors(.:format) visitors#create
home /home(.:format) pages#home
root / high_voltage/pages#show {:id=>"home"}
page GET /pages/*id high_voltage/pages#show