我一直在試圖設置一個聯繫表格,但我不斷收到錯誤,我只是無法弄清楚我做錯了什麼。我得到的最新的錯誤是:Rails - Form_for錯誤的未定義的局部變量?
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 %>
感謝您的任何幫助!
謝謝,非常完美。我想我被卡住了,因爲我有另一個不使用@variable名稱的表單,它工作正常。不能完全解決這個問題:/ – Stephen
@Stephen嘗試保持命名約定一致以避免這樣的問題 - 儘量在表單上儘量使用實例變量。 – ArtOfCode
謝謝@ArtOfCode,我會這麼做的! – Stephen