我想将输入的“电子邮件”从静态页面保存到数据库。现在,我有一个带有 :address 字段的电子邮件模型,但是单击提交输入时我无法保存该值。
带表格的布局
# layout/website.html.erb
<div>
<%= form_for @email, :url => newsletter_path, :method => :post do |email| %>
<%= email.text_field :address %>
<%= email.submit "Go" %>
<% end %>
</div>
页面控制器
# controllers/pages_controller.rb
def home
newsletter
end
def newsletter
@email = Email.new(params[:address])
if @email.valid?
redirect_to(request.referer, :notice => "The suscription has been sent successfully.")
else
redirect_to(request.referer, :alert => "Please add an valid email address.")
end
end
路线
# routes.rb from static pages
get "/home" => 'pages#home', :as => :home
get "/pricing" => 'pages#pricing', :as => :pricing
get "/logo-gallery" => 'pages#logo_gallery', :as => :logo_gallery
get "/blog" => 'pages#blog', :as => :blog
get "/blog/:id" => 'pages#post', :as => :post
get "/contact" => 'pages#contact', :as => :contact
match '/contact' => 'pages#create', :as => :contact, :via => :post
get "/faqs-and-terms" => 'pages#faqs_and_terms', :as => :faqs_and_terms
match "/newsletter" => 'pages#newsletter', :as => :newsletter, :via => :post
模型
# models/email.rb
class Email < ActiveRecord::Base
attr_accessible :address
validates :address, :format => { :with => %r{.+@.+\..+} }, :allow_blank => true
end
使用此代码,当我现在访问 /home 时收到:
ActionController::ActionControllerError in PagesController#home
Cannot redirect to nil!
我希望你能帮助我,我能做些什么来解决这个问题并获得更好的代码。谢谢你。