我正在制作基于Futureme.org的单页应用程序进行练习。用户进入主页,看到一个表单,将他们的电子邮件地址,主题和邮件正文发送给他们。
我遇到的问题是我收到错误“表单中的第一个参数不能包含nil或为空”。这是我的代码;
模型;
class Letter < ActiveRecord::Base
VALID_EMAIL_REGEX = /\A[\w+\-,]+@[a-z\d\-.]+\.[a-z]+\z/i
validates_presence_of :email, presence: true, format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
validates_length_of :subject, presence: true, length: { maximum: 50 }
validates_presence_of :message
end
控制器;
class LettersController < ApplicationController
def new
@letter = Letter.new
end
def create
@letter = Letter.new(params[:letter])
if @letter.save
redirect_to letters_path, :notice => "Your letter was sent!"
else
render "new"
end
end
end
查看表单;
<%= form_for @letter, :html => {:class => 'form-horizontal'} do |f| %>
<% if @letter.errors.any? %>
<div class="error_messages">
<h2><%= pluralize(@letter.errors.count, "error")%>stopped this message from being saved</h2>
<ul>
<% @letter.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
<% end %>
<div class="field">
<%= f.label :email %><br />
<%= f.text_field :email %>
</div>
<div class="field">
<%= f.label :subject %><br />
<%= f.text_field :subject %><br />
</div>
<div class="field">
<%= f.label :message, "Message" %><br />
<%= f.text_area :message, size: "60x10" %>
</div>
<div class="actions"><%= f.submit "Submit", class: "btn btn-small btn-primary" %></div>
<% end %>
表单位于“欢迎控制器”中的主页上。
任何帮助都会很棒。
答案 0 :(得分:1)
当在其他视图上绘制表单时,看起来您在操作new
中构建了字母:)
您应该将@letter = Letter.new
移至适当的操作
其中一个变体是:
#WelcomeController
def home
@letter = Letter.new
end
#LettersController
def create
@letter = Letter.new(params[:letter])
if @letter.save
redirect_to letters_path, :notice => "Your letter was sent!"
else
render "welcome/home"
end
end
如果您准备好一些数据home
,请务必小心,因为您渲染“welcome / home”视图,因此在验证失败时应该关注初始化操作create