views:

146

answers:

1

The functionality I'm looking for: I have a form that will search my 'Proposal' model. I want the form to contain a select box and display the categories I have. Now, 'category' is merely a column in my 'Proposal' Model, so the following code from railscasts does not work (as it assumes a category table and use of category_id)

      <%= f.collection_select :category_id_equals, Category.all, :id, :name, :include_blank => true %>

The closest thing I got was

<%= f.collection_select :category_equals, Proposal.category_like(""), :id, :category, :include_blank => true %>

This would work perfect if it only brought uniques from the category column, not repeating cases :-/.

Also...this leads me to question -- should I utilize category_id instead and create a categories table even though it would just have and id and name column?

Thanks in advance :-)

+2  A: 

First off, yes you should put those categories in their own model. Or consider a plug-in like acts_as_taggable* A category is an entity in your application and should exists as such.

  1. Adding it as a model lets you easily force users to choose from the list and maintain the list.
  2. You can someday add a visible boolean if you want to hide some old categories from the view. You could just add a visible named_scope to easily query for the items to populate the collection_select with.
  3. Making the category a model will also let you know when each category was created.

If you want to hack together something with what you've got, you could load up those objects, put their categories into an array and then do array.uniq! to get just the ones you want.

You could add a method to Proposal that returns the unique categories.

def self.unique_categories
  categories = []
  Proposal.all.each do |p|
    categories << p.category
  end
  categories.uniq
end
danivovich
Thanks danvino for giving me a complete answer. I will add a category model since it will make the short term problem easier and probably future ones as well.Thanks.
MrCheetoDust