我开始在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
app/views/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'
我发现这个错误是与打字错误有关,但这似乎不是我的情况。这可能是一个愚蠢的错误,但我找不到它。有人能帮帮我吗?
正如@Robert在他的评论中已经指出的那样,您需要用小写字母命名您的Contato
模型文件。
然而,由于Ruby正在控制器本身(ContatosController::Contato
)中寻找您的模型,您可以通过在模型名称之前放置双冒号来解决此问题,如:
@contato = ::Contato.new
这将强制Ruby解释器在"root/top"命名范围中查找Contato
模型。