0

This is a really simple question but I am new. I am trying to create a dropdown menu with values populated from the model. However, instead of displaying the city names, I am getting the record id's like: 0x007fee0b7442c0 (not sure if these are called id's, I think there is another term).

Controller:

@cities = City.find(:all, select: "name")

View:

<%= f.select(:city, @cities) %>

What am I doing wrong?

4

5 回答 5

2

尝试:选择(对象,方法,选择,选项 = {},html_options = {})

@cities = City.select(:name)
<%= f.select(:city, @cities.collect {|p| [ p.name, p.name ] }) %>
于 2013-05-06T06:03:12.277 回答
2

如果您只想要name数据库中的属性,请执行以下操作:

@cities = City.pluck(:name)
# => ["Sydney", "Melbourne", "Canberra"]
于 2013-05-06T06:11:08.443 回答
0

这里有使用 collection_select 的指南

http://www.fmhcc.com.au/ruby/rails/using-collection_select-in-rails/

于 2013-05-06T06:11:44.837 回答
0

你也可以@cities = City.find(:all, select: "name")通过做来改进

@cities = City.pluck(:name)
于 2013-05-06T06:14:18.800 回答
0

如果要在选择框中显示城市名称,并且要在表单提交时将城市 id 作为参数传递,请使用此

f.select :city, @cities.map {|c| [ c.name, c.id ] }
于 2013-05-06T06:24:37.267 回答