开发者

Rails way to implement a simple dropdown

开发者 https://www.devze.com 2023-03-25 05:13 出处:网络
I have a simple dropdown that I want to populate from a model. I don\'t want to bind it to another model at all, just a simple standalone form with a list of items and handle storing the state of the

I have a simple dropdown that I want to populate from a model. I don't want to bind it to another model at all, just a simple standalone form with a list of items and handle storing the state of the dropdown in a session variable, I can achieve it with a more brute force approach as shown but it doesn't feel very 'rails' to 开发者_如何学JAVAme.

<form action='/home/switch' method='post'>
    <select name="all_items">
    <% @items.each do |i| %>
        <option value="<%= i.id %>" <%= i.id.to_s == session[:current_item] ? "selected" : "" %>><%= i.name %></option>
    <% end %>
    </select>
    <input type="submit">
</form> 

Is there a better way to do this in Rails?

Update: Yep. collection_select worked for me:

<%= collection_select(:item, :id, Item.all, :id, :name, {:selected => session[:current_item].id}) %>


Take a look at form_tag, select_tag, options_from_collection_for_select, and/or collection_select.

So your example might look like this (not tested, may have typos)

<%= form_tag('/home/switch') do %>
<%=   select_tag('all_items', options_from_collection_for_select(@items, 'id', 'name')) %>
<%=   submit_tag %>
<%= end %>

This is missing the "selected" bit, take a look at the docs for that.

0

精彩评论

暂无评论...
验证码 换一张
取 消