Search logic functionality
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 :-)
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.
- Adding it as a model lets you easily force users to choose from the list and maintain the list.
- 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 thecollection_select
with. - 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
精彩评论