这是一个非常基本的问题,但我很难将它整合到我的应用程序中。我已经查看了关于 SO 的其他类似问题,但它们都将联系页面用作单独的页面。
我有一个 Rails 应用程序的前端,它只是一个面向公众的小型网站,使用 stellar.js 进行视差滚动。
在页面的最后部分,我想要一个“联系我们”表格,但我得到了一个
NoMethodError in Welcome#index undefined method `model_name' for NilClass:Class
以下是相关文件:
路线.rb
TestApp::Application.routes.draw do
get "welcome/index"
root :to => 'welcome#index'
match 'contact' => 'contact#new', :as => 'contact', :via => :get
match 'contact' => 'contact#create', :as => 'contact', :via => :post
app/views/welcome/index.html.erb
<%= render "contact" %>
页面 app/views/welcome/_contact.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
消息.rb
class Message
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
attr_accessor :name, :email, :subject, :body
validates :name, :email, :subject, :body, :presence => true
validates :email, :format => { :with => %r{.+@.+\..+} }, :allow_blank => true
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
end
def persisted?
false
end
end
问题是我需要做什么才能使此表单在welcome#index 视图中正常运行?