如何将静态页面的输入保存到rails中的数据库

时间:2013-09-05 06:55:44

标签: ruby-on-rails forms routes

我想将输入“电子邮件”从静态页面保存到数据库。现在,我有一个带有:地址字段的电子邮件模型,但是当点击提交输入时我无法保存该值。

带表单的布局

# 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!

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

2 个答案:

答案 0 :(得分: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来检查表单发送的params。

答案 1 :(得分:1)

在简报行动中,电子邮件记录仅初始化但未保存。而且你不需要每次都在家庭活动中调用通讯方法。只需像这样更新你的代码。

页面控制器

# 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未在控制器中定义,因此您应该初始化表单中的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>

我希望它能起作用。