0

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

查看 root 的 static_pages#home

<%= 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 %>
4

1 回答 1

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
于 2013-09-03T08:50:07.743 回答