Ruby on rails Rails 3.2.18:ActiveRecord如何从一条语句转换为下一条语句?
我正在开发一个Rails 3.2.18应用程序,它使用一个名为Ruby on rails Rails 3.2.18:ActiveRecord如何从一条语句转换为下一条语句?,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,我正在开发一个Rails 3.2.18应用程序,它使用一个名为Address的ActiveRecord。这段代码的工作原理与您预期的一样: <% addresses = Address.where(user_id: user.id) %> <% addresses.each do |address| %> <td><%= address.address1 %><br /><%= address.city %>, <%=
Address
的ActiveRecord
。这段代码的工作原理与您预期的一样:
<% addresses = Address.where(user_id: user.id) %>
<% addresses.each do |address| %>
<td><%= address.address1 %><br /><%= address.city %>, <%= address.state %> <%= address.zip %></td>
<% end %>
一切都很好,但我一加上这句话:
<%= a.city %>
城市的定义在哪里?您在哪里添加代码行a.city?此外,它不会“选择一个地址”-它会返回一个ActiveRecord::具有用户id的所有地址的关系:
user.id
。这就是为什么您可以首先对它调用
——如果它是一个地址对象,您就不能。(1)“城市”是我的数据库中“地址”表中的一个字段,与地址ActiveRecord关联。(2) 我在“a.class”之后添加了“a.city”,但这并不重要——在定义了a
之后的任何地方添加它都会导致错误。(3) 表中只有一行具有指定的user\u id
,但我仍然可以对其进行迭代,显然,可以首先调用
。一个关系可以有任意数量的元素-零个、一个或多个-并且它始终是可枚举的。您可以将错误的整个回溯添加到问题中吗?
<%= a.city %>
Showing /home/creede/rails/marches2-dev/app/views/stations/index.html.erb where line #49 raised:
undefined method `city' for nil:NilClass
Extracted source (around line #49):
46: <%= debug(a) %>
47: <%= a.nil? %>
48: <%= a.class %>
49: <%= a.city %>
50: <% addresses.each do |address| %>
51: <td><%= address.address1 %><br /><%= address.city %>, <%= address.state %> <%= address.zip %></td>
52: <% end %>
Rails.root: /home/creede/rails/marches2-dev
Application Trace | Framework Trace | Full Trace
app/views/stations/index.html.erb:49:in `block in _app_views_stations_index_html_erb___174412722496690062_69855565287900'
app/views/stations/index.html.erb:29:in `each'
app/views/stations/index.html.erb:29:in `_app_views_stations_index_html_erb___174412722496690062_69855565287900'
app/controllers/stations_controller.rb:7:in `index'
actionpack (3.2.18) lib/action_view/template.rb:145:in `block in render'
activesupport (3.2.18) lib/active_support/notifications.rb:125:in `instrument'
actionpack (3.2.18) lib/action_view/template.rb:143:in `render'
actionpack (3.2.18) lib/action_view/renderer/template_renderer.rb:47:in `block (2 levels) in render_template'
actionpack (3.2.18) lib/action_view/renderer/abstract_renderer.rb:38:in `block in instrument'
activesupport (3.2.18) lib/active_support/notifications.rb:123:in `block in instrument'
activesupport (3.2.18) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
activesupport (3.2.18) lib/active_support/notifications.rb:123:in `instrument'