1

我创建了一个表单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 %>

客户端.rb

class Client < ActiveRecord::Base
  attr_accessible :email, :name
  has_one :city
  accepts_nested_attributes_for :city
end

城市.rb

class City < ActiveRecord::Base
  attr_accessible :client_id, :name
  belongs_to :client
  has_many :streets
  accepts_nested_attributes_for :streets
end

街道.rb

class Street < ActiveRecord::Base
  attr_accessible :city_id, :name
  belongs_to :city
end

clients_controller.rb [由脚手架生成]

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 %>

路线.rb

 resources :clients do
    resources :cities do
      resources :streets
    end
  end
4

2 回答 2

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 ..

于 2013-05-04T14:49:03.283 回答
0

还要确保您build_association用于关联has_oneassociations.build.has_many

# has_one :city
@city = @client.build_city

# has_many :streets
@street = @city.streets.build
于 2013-05-04T14:52:01.827 回答