简单的通讯形式

时间:2013-09-03 08:43:45

标签: ruby-on-rails ruby-on-rails-3

所以我有一个static_pages #home,我希望人们将他们的电子邮件地址放在一个表单中,这将把它保存到我的NewslettersController中的数据库中。但我不能为我工作,我可以输入我的电子邮件地址并按提交但不会保存到数据库或在模型中验证。

查看static_pages #home是root

<%= form_for Newsletter.new, :url => { :controller => "newsletters", :action => "create" } do |f| %>
  <%= f.text_field :email, :style => "width:50%;", :placeholder => "Your email address", :class => "form-control input-sm" %>
  <%= f.submit "Keep me updated", :class => "btn btn-primary btn-sm" %>
<% end %>

模型

class Newsletter < ActiveRecord::Base
  attr_accessible :email

  validates_uniqueness_of :email
  validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
end

控制器

class NewslettersController < ApplicationController

  def create
    @newsletter = Newsletter.new(params[:newsletter])

    respond_to do |format|
      if @newsletter.save
        format.html { redirect_to root_path, notice: 'You will hear from us shortly, Thank You' }
      else
        format.json { render json: @newsletter.errors, status: :unprocessable_entity }
      end
    end
  end

end

  resources :newsletters, :only => :create

编辑:

查看

<%= form_for @newsletter do |f| %>
  <%= f.text_field :email, :style => "width:50%;", :placeholder => "Your email address", :class => "form-control input-sm" %>
  <%= f.submit "Keep me updated", :class => "btn btn-primary btn-sm" %>
    <% if @newsletter.errors.any? %>
      <div id="error_explanation">
        <h2><%= pluralize(@newsletter.errors.count, "error") %> prohibited this email address from being saved:</h2>

        <ul>
        <% @newsletter.errors.full_messages.each do |msg| %>
          <li><%= msg %></li>
        <% end %>
        </ul>
      </div>
    <% end %>
<% end %>

1 个答案:

答案 0 :(得分:0)

您可以像这样重构代码:

应用/控制器/ static_pages.rb

def home
  @newsletter = Newsletter.new
end

在您看来:

<%= form_for @newsletter do |f| %>

关于您的问题,您可能需要检查@newsletter.errors以查看验证过程是否成功。

尝试:

class NewslettersController < ApplicationController

  respond_to :html

  def create
    @newsletter = Newsletter.new(params[:newsletter])
    @newsletter.save

    respond_with @newsletter
  end
end