所以我有一个 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 %>