rails collection_select vs. select

后端 未结 3 1686
隐瞒了意图╮
隐瞒了意图╮ 2021-01-31 08:44

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

3条回答
  •  鱼传尺愫
    2021-01-31 08:52

    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:

    
    

    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

提交回复
热议问题