我创建了一个表格,使用scaffold
,然后创建Models
来制作一个nested model
但我的浏览器出现错误,我无法解决它,我在这里寻找帮助,这个错误:未定义的局部变量或方法`城市'ROR
NameError in Clients#new
line #33 raised:
undefined local variable or method `city' for #<#<Class:0xc4fb5bc>:0xb704f94>
Extracted source (around line #33):
30: <% end %>
31: </div>
32: <div class="field">
33: <%= city.fields_for :street do |street| %>
34: <%= street.label :street %>
35: <%= street.text_field :name %>
36: <% end %>
Client.rb
class Client < ActiveRecord::Base
attr_accessible :email, :name
has_one :city
accepts_nested_attributes_for :city
end
city.rb
class City < ActiveRecord::Base
attr_accessible :client_id, :name
belongs_to :client
has_many :streets
accepts_nested_attributes_for :streets
end
[由脚手架生成]
def new
@client = Client.new
@city = @client.build_city
@street = @city.build_street # I don't know should I add this line or not
respond_to do |format|
format.html # new.html.erb
format.json { render json: @client }
end
end
形式street.rb
class Street < ActiveRecord::Base
attr_accessible :city_id, :name
belongs_to :city
end
clients_controller.rb
<%= form_for(@client) do |f| %>
<% if @client.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@client.errors.count, "error") %> prohibited this client from being saved:</h2>
<ul>
<% @client.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :email %><br />
<%= f.text_field :email %>
</div>
<div class="field">
<%= f.fields_for :city do |city| %>
<%= city.label :city %>
<%= city.text_field :name %>
<%= city.fields_for :street do |street| %>
<%= street.label :street %>
<%= street.text_field :name %>
<% end %>
<% end %>
</div>
<div class="field">
</div>
<div class="actions">
<%= f.submit "Submit Client", class: "btn btn-large btn-primary" %>
</div>
<% end %>
的routes.rb
resources :clients do
resources :cities do
resources :streets
end
end
我没有和我的客户得到了以下NameError#新 /_form.html.erb其中线#29提出: 未定义的局部变量或方法'城市”为#<#<类别:0xb9b0e8c> :0xb9aeed4> 提取的源(围绕线#29): 26:\t <% end %> 27:
我修改了我的答案 – Mattherick 2013-05-04 14:56:56
它提出了同样的错误 – 2013-05-04 15:02:00