我正在使用以下教程将联系表单放在一起:http://matharvard.ca/posts/2011/aug/22/contact-form-in-rails-3/
我已按照所有说明操作,但出于某种原因,当我尝试访问应用中的“联系”页面时,我一直收到此错误:
NoMethodError in Contact#new
undefined method `[]' for nil:NilClass
Extracted source (around line #1):
1: <%= form_for @message, :url => contact_path do |form| %>
2: <fieldset class="fields">
3: <div class="field">
4: <%= form.label :name %>
我在这里缺少什么?
new.html.erb
<%= form_for @message, :url => contact_path do |form| %>
<fieldset class="fields">
<div class="field">
<%= form.label :name %>
<%= form.text_field :name %>
</div>
<div class="field">
<%= form.label :email %>
<%= form.text_field :email %>
</div>
<div class="field">
<%= form.label :subject %>
<%= form.text_field :subject %>
</div>
<div class="field">
<%= form.label :body %>
<%= form.text_area :body %>
</div>
</fieldset>
<fieldset class="actions">
<%= form.submit "Send" %>
</fieldset>
<% end %>
contact_controller.rb
class ContactController < ApplicationController
def new
@message = Message.new
end
def create
@message = Message.new(params[:message])
if @message.valid?
NotificationsMailer.new_message(@message).deliver
redirect_to(root_path, :notice => "Message was successfully sent.")
else
flash.now.alert = "Please fill all fields."
render :new
end
end
end
notifications_mailer.rb
class NotificationsMailer < ActionMailer::Base
default :from => "myemail@gmail.com"
default :to => "myemail@gmail.com"
def new_message(message)
@message = message
mail(:subject => "[myemail@gmail.com] #{message.subject}")
end
end
答案 0 :(得分:2)
我在本教程中遇到了类似的问题。这是因为我忘了从Message类中删除< ActiveRecord::Base
。我也忘记将attr_accessible
更改为attr_accessor
。你可能想要仔细检查这两点。