Rails - Creating a select tag from a object hash

前端 未结 4 2103
无人及你
无人及你 2021-02-18 23:13

I need to create a select box from the values available in a Hash.

For instance, I have a \'thing\' and the \'thing\' has a variety of status fields:

1 =         


        
相关标签:
4条回答
  • 2021-02-18 23:49

    Just as Schrockwell has said:

    Hash.each |a| returns an array of the form a = [key, value], so for the hash @status_fields you can write:

    <%= collection_select('thing', 'status', @status_fields, :first, :last) %>
    

    Alternatively, if you'd like the key to show up in the select list and the value point to the select list value, then:

    <%= collection_select('thing', 'status', @status_fields, :last, :first) %>
    

    This will select the option given by thing.status or nothing if nil is returned

    If you want to just create any selection not tied to an object use

    <%= select_tag('name', options_from_collection_for_select(@status_fields, :first, :last, '2')) %>
    

    where '2' is the index of the desired selection

    PS: I don't have enough reputation to just amend the original post or comment on it

    0 讨论(0)
  • 2021-02-18 23:49

    The select helper method will accept a hash in the form { text_displayed_in_select => select_value }, so you'll probably want to invert that hash.


    0 讨论(0)
  • 2021-02-18 23:58

    you could do something like

    select "foo", "bar", @hash_object
    

    or

    select "foo", "bar", @hash_object.map { |h| [h.key, h.value] }
    

    I'd probably invert your hash first to make the key point to the value

    0 讨论(0)
  • 2021-02-18 23:58

    Hash.each |a| returns an array of the form a = [key, value], so for the hash @status_fields you can write:

    <%= collection_select('thing', 'status', @status_fields, :first, :last) %>
    

    Alternatively, if you'd like the key to show up in the select list and the value point to the select list value, then:

    <%= collection_select('thing', 'status', @status_fields, :last, :first) %>
    
    0 讨论(0)
提交回复
热议问题