Rails - Form_for未定义局部变量的错误?

时间:2016-09-04 13:04:41

标签: ruby-on-rails forms variables

我一直试图设置联系表单,但我一直在收到错误,而我却无法弄清楚我做错了什么。我得到的最新错误是:

NameError in Contacts#new
Showing .../app/views/contacts/new.html.erb where line #2 raised:

undefined local variable or method `contact' for #<#<Class:0x007fa2933ca1f8>:0x007fa29a4df460>
Did you mean?  @contact
           concat
Extracted source (around line #2):
1
2
3
4
5
6

<h1>Contact us</h1>
<%= form_for(contact) do |f| %>
  <div class="field entry_box">
  <%= f.label :name %>
  <%= f.text_field :name, class: "form-control entry_field" %>
</div>

我的ContactsController

class ContactsController < ApplicationController

def new
    @contact = Contact.new
end

def create
    @contact = Contact.new(contact_params)
    if @contact.save
    redirect_to contacts_path, notice: "Thanks for contacting us!"
  else
    render :new
  end
end

private

def contact_params
    params.require(:contact).permit(:name, :email, :message)
end

end

模型

class Contact < ApplicationRecord
end

路线(相关部分)

resources :contacts, only: [:new, :create]

get "contact" =>'contacts#new'
post "contact" =>'contacts#create'

查看(new.html.erb)

<h1>Contact us</h1>
<%= form_for(contact) do |f| %>
  <div class="field entry_box">
  <%= f.label :name %>
  <%= f.text_field :name, class: "form-control entry_field" %>
</div>

<div class="field entry_box">
  <%= f.label :email %>
  <%= f.number_field :email, class: "form-control entry_field" %>
</div>

<div class="field entry_box">
  <%= f.label :message %>
  <%= f.text_field :message, class: "form-control entry_field" %>
</div>

<div class="actions center space_big">
  <%= f.submit "Submit", class: "btn btn-lg btn-success" %>
</div>
<% end %>

感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

contact中的变量undefinednew.html.erb。请参阅rails建议使用@contact

该行

<%= form_for(contact) do |f| %>

应该是

<%= form_for(@contact) do |f| %>

实例变量@contactnew的{​​{1}}操作传递到视图。

答案 1 :(得分:1)

您的控制器定义了一个实例变量da db dc,但您的视图使用@contact。有所不同 - 请确保您的contact调用使用控制器定义的form_for变量。

你有:

@contact

你应该改为

<%= form_for(contact) do |f| %>

因为控制器中的这一行

<%= form_for(@contact) do |f| %>

在大多数错误中,Rails会为您提供导致异常的源代码和行号,然后会给您一个提示 - 在这种情况下,它表示“您的意思是@contact = Contact.new 吗?”

答案 2 :(得分:0)

您必须以新的形式编写实例变量,只需编写

即可
<%= form_for(@contact) do |f| %>
<% end %>