2

我想将输入的“电子邮件”从静态页面保存到数据库。现在,我有一个带有 :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!

我希望你能帮助我,我能做些什么来解决这个问题并获得更好的代码。谢谢你。

4

2 回答 2

3

您应该使用Email.create(params[:email])而不是Email.new(params[:address])在数据库中保留记录。此外,在您看来,您的代码添加 hidden_​​field

<%= email.text_field :address %>
<%= hidden_field_tag :referer, :value => request.path %>
<%= email.submit "Go" %>

然后在控制器中:

redirect_to params[:referer]

UPD 另外,请注意您应该params[:email]在控制器中使用,而不是params[:address]. 您可以在控制器中调用raise params.inspect以检查表单发送的参数。

于 2013-09-05T07:03:17.657 回答
1

在时事通讯操作中,电子邮件记录仅被初始化但不被保存。而且您无需每次都在 home 操作中调用 newsletter 方法。只需像这样更新您的代码。

页面控制器

# controllers/pages_controller.rb
.....
# no need to call newsletter action here
def home      
end

def newsletter
  @email = Email.new(params[:email])

  if @email.save
    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

带表格的布局

由于@email 未在控制器中定义,因此您应该在表单中初始化一个电子邮件对象。

# layout/website.html.erb
<div>
  <%= form_for Email.new, :url => newsletter_path, :method => :post do |email| %>
    <%= email.text_field :address %>
    <%= email.submit "Go" %>
  <% end %>
</div>

我希望它应该工作。

于 2013-09-05T07:27:18.707 回答