我开始在ROR中发展。我现在正在做的用户历史记录是联系页面。 MVC的代码如下:
应用/控制器/ contatos_controller.rb
class ContatosController < ApplicationController
def new
@contato = Contato.new
end
def create
@contato = Contato.new(secure_params)
if @contato.valid?
flash[:notice] = "Mensagem enviada de #{@contato.name}."
redirect_to root_path
else
render :new
end
end
private
def secure_params
params.require(:contato).permit(:name, :subject, :email, :content)
end
end
应用/模型/ Contato.rb
class Contato
include ActiveModel::Model
attr_accessor :name, :string
attr_accessor :subject, :string
attr_accessor :email, :string
attr_accessor :content, :string
validates_presence_of :name
validates_presence_of :subject
validates_presence_of :email
validates_presence_of :content
validates_format_of :email,
with: /\A[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}\z/i
validates_length_of :content, :maximum => 500
end
应用/视图/ contatos / new.html.erb
<h3>Contato</h3>
<div class="form">
<%= simple_form_for @contato do |form| %>
<%= form.error_notification %>
<%= form.input :name, autofocus: true %>
<%= form.input :subject %>
<%= form.input :email %>
<%= form.input :content, as: :text %>
<%= form.button :submit, 'Submit', class: 'submit' %>
<% end %>
</div>
配置/ routes.rb中
Rails.application.routes.draw do
resources :contatos, only: [:new, :create]
root 'static_pages#home'
end
当我尝试访问http://localhost:3000/contatos/new时,会显示以下错误:
NameError in ContatosController#new
uninitialized constant ContatosController::Contato
app/controllers/contatos_controller.rb:4:in `new'
我发现这个错误的原因是它与拼写错误有关,但这似乎不是我的情况。这可能是一个愚蠢的错误,但我找不到它。有人能帮助我吗?
答案 0 :(得分:0)
正如@Robert在评论中已经提到的那样,您需要将您的Contato
模型文件命名为小写。
但是,由于Ruby在控制器本身(ContatosController::Contato
)中寻找您的模型,您可以通过在模型名称之前放置双冒号来解决此问题,如下所示:
@contato = ::Contato.new
这会强制Ruby解释器在“root / top”名称范围内查找Contato
模型。