rails collection_select vs. select

匿名 (未验证) 提交于 2019-12-03 02:45:02

问题:

collection_select and select Rails helpers: Which one should I use?

I can't see a difference in both ways. Both helpers take a collection and generates options tags inside a select tag. Is there a scenario where collection_select is better than select? or is anything I am missing here?

回答1:

collection_select is intended to be used when the list of items is an array of ActiveRecord objects. collection_select is built on the top of select so it's a convenient method when you need to display a collection of objects and not an array of strings.

collection_select(:post, :author_id, Author.find(:all), :id, :name) 


回答2:

I have written something on that a while back, have a look at http://nasir.wordpress.com/2007/11/02/not-binding-your-selection-list-to-a-particular-model-in-rails/

Hope that helps



回答3:

And regarding select, you can use it with a Hash. I used to use it with ENUM.

# In a hypothetical Fruit model enum types: { 'Banana' => 0, 'Grape' => 1, 'Mango' => 2 }  # In the view f.select :type, Fruits.types.invert 

Note that I had to use invert in order to show the correct value in option:

<select>   <option value="0">Banana</option>   <option value="1">Grape<option>   <option value="2">Mango</option> </select> 

To refer to it in a show file you can use Fruit.types and this will return our previous Hash. This way you can do:

 Fruit.types[obj.type] 

Last note: You can use symbols instead numbers if you prefer enum types: { 'Banana' => :banana, ...and you will get <option value="banana">Banana</option>



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!