Topic: A better way to do this? (select field)

Right now I have it so this following code can let me specify a category:

<p><label for="link_category">Category</label><br/>
<select name="link[category_id]">
<% @categories.each do |category| %>
<option value="<%= category.id %>">
    <%= category.title %>
</option>
<% end %>
</select>
</p>

First, I don't think this looks pretty enough for rails.

Second, it has a problem. If I update a field (for instance, making something approved) and then click edit. The category is default on the first field, so any time I update it's going to switch the category to the first category in the drop down, instead of defaulting to the category that is already set.

How would I implement that functionality so it defaults to the category if one is already set?

Thanks.

http://danielfischer.com - Personal Web-Technology-Blog, Los Angeles.

Re: A better way to do this? (select field)

Rails has a nice helper called collection_select which can do everything for you.

<%= collection_select :link, :category_id, @categories, :id, :title %>

Railscasts - Free Ruby on Rails Screencasts

Re: A better way to do this? (select field)

Ahh, I ended up using this

<%= select("link", "category_id", Category.find_all.collect {|c| [c.title, c.id] }, {:include_blank => true} ) %>

I assume the one you gave me would let me get rid of the Category.find_all smile

Thanks!

http://danielfischer.com - Personal Web-Technology-Blog, Los Angeles.

Re: A better way to do this? (select field)

DFischer wrote:

I assume the one you gave me would let me get rid of the Category.find_all smile

You still need to do a find on Category (which was the @categories instance variable). The advantage of collection_select is you don't have to do "collect" and place the attributes in the arrays.

BTW, Category.find_all is deprecated, best to use Category.find(:all)

Railscasts - Free Ruby on Rails Screencasts

Re: A better way to do this? (select field)

Alright, in that case I have a lot of (now) Category.find(:all) in my code.

new, create, edit, etc

Is there a way I can dry this up?

Last edited by DFischer (2006-12-29 20:52:26)

http://danielfischer.com - Personal Web-Technology-Blog, Los Angeles.

Re: A better way to do this? (select field)

do you mean you are creating those selects all over the place? you can just stick it in a helper method, perhaps in application_helper.rb, and just call the helper.

def category_select(model='link')
   select(model, 'category_id', Category.find(:all).collect {|c| [c.title, c.id] }, {:include_blank => true})
end

Last edited by tortoise (2006-12-29 20:59:14)

Re: A better way to do this? (select field)

No, I meant in my controller I keep having to put the same instance variable over and over.

http://danielfischer.com - Personal Web-Technology-Blog, Los Angeles.