Rails 5:使用options_from_collection_for_select从数据库填充下拉列表

时间:2016-11-02 04:15:39

标签: ruby-on-rails forms activerecord

我是rails的新手并且已经阅读过关于下拉的文档,但我仍在努力。

我有一个数据库如下:

                        Table "public.lakeaddresses"
Column  |         Type          | Modifiers | Storage  | Stats target | Description
---------+-----------------------+-----------+----------+--------------+-------------
 address | character varying(40) |           | extended |              |
 city    | character varying(25) |           | extended |              |
 state   | character varying(20) |           | extended |              |
 zip     | integer               |           | plain    |              |
 county  | character varying(25) |           | extended |              |
 lake    | character varying(30) |           | extended |              |
 lakeid  | integer               |           | plain    |              |

我想创建一个下拉列表,填充湖泊的名称,这将是“湖”列

视图/图/ index.html.erb

<head>
<script src='https://api.mapbox.com/mapbox-gl-js/v0.26.0/mapbox-gl.js'>    
</script>
<link href='/home/garrett/lakemag/app/assets/stylesheets/lakemap.css' rel='stylesheet' />
</head>          

<body>
<div  id='map' style='margin:0 auto; width: 1024px; height: 768px;'>
<script>
  mapboxgl.accessToken = 'pk.eyJ1IjoiZ3JhZmZpbmR1c3RyaWVzIiwiYSI6ImNpdXAxY2pycjAxeGoyb251dDY2emNqeXgifQ.YtJkR5Elp-oq3FaMTUlXyw';
  var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/graffindustries/ciursnqrv009u2js5cpedcnsr'
  });
</script>
</div>

</br></br>

<center>

<% form_tag(method: "get") do %>
  <% lake_array = Lake.all.map { |lake| [lake.name] } %>
  <= select_tag 'Lake Name', options_for_select(lake_array) %>
<% end %>

</center>
</body>

控制器/ map_controller.rb

def new
@lake = Lake.all

收到错误:

ActionView::Template::Error (uninitialized constant ActionView::CompiledTemplates::Lake
18:
19: <center>
20:
21: <% form_tag(method: "get") do %>
22: <% lake_array = Lake.all.map { |lake| [lake.name] } %>
23: <= select_tag 'Lake Name', options_for_select(lake_array) %>
24: <% end %>
25:
26: </center>
F, [2016-11-02T06:22:04.619269 #7096] FATAL -- : [f4086edc-8de8-4b36-9b81-4a20efbde333] app/views/map/index.html.erb:21:in `_app_views_map_index_html_erb___3432893749292109102_24860500'

1 个答案:

答案 0 :(得分:0)

而不是<% options = options_from_collection_for_select(@lake, 'lake') %>

尝试以这种方式建立阵列。

<% lake_array = Map.all.map { |map| [map.lake] } %>
<%= select_tag 'Lake Name', options_for_select(lake_array) %>

请注意,除非您使用的是form_for,否则您无法使用f.select,而是必须使用select_tag

更新:您收到错误是因为lake来自map表。如果你有一个带有表格列lake.rb的{​​{1}}模型,你可以在rails控制台中执行类似的操作。

name

但是现在,由于您无法像这样访问lake = Lake.first lake_name = lake.name ,因此您必须通过Lake.method访问它。因此,例如,为了访问您的某个湖泊名称,您必须在rails控制台中执行此操作。

Map

希望这可以解决您的疑问并解释您收到错误的原因。