我使用scaffold
创建了一个表单,然后创建了Models
来制作nested model
,但我的浏览器出错,我无法解决,我在这里寻求帮助,我收到了这个错误:
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
street.rb
class Street < ActiveRecord::Base
attr_accessible :city_id, :name
belongs_to :city
end
clients_controller.rb [由scaffold生成]
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
表格
<%= 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
答案 0 :(得分:0)
您必须更改模型:
class City < ActiveRecord::Base
attr_accessible :client_id, :name
belongs_to :client
has_many :streets
accepts_nested_attributes_for :streets # add the "s"!
end
您必须修改_form.html.erb
<%= city.fields_for :streets do |street| %> ## add also the "s"
<%= street.label :street %>
<%= street.text_field :name %>
<% end %>
你还必须修改你的控制器就像mind.blank在他的回答中说的那样。
顺便说一句,也许这可以帮助你更好地理解accepts_nested_attributes_for ..
答案 1 :(得分:0)
另外,请务必使用build_association
表示has_one
关联,associations.build
表示has_many
。
# has_one :city
@city = @client.build_city
# has_many :streets
@street = @city.streets.build