I have a model that has a belongs_to association to categories.
Example:
- Thing
- belongs_to :category
- Category
- has_one :thing
Should I make a view file for each category to find the given category, example:
views/things/category_name1.html.erb
vi开发者_C百科ews/things/category_name2.html.erb
views/things/category_name3.html.erb
views/things/category_name4.html.erb
Or is there a more convenient way to do this?
The views are the same for each category except for the category name in the find
method. I have tried this:
<%= Thing.find(:all, :conditions => {:category => 'Name of category'}) %>
I want my url to be /category_name/name_of_thing
.
The friendly_id gem will handle the URL generation that you're looking for. In your routes, you'll want to have something along the lines of (Rails 3). You do not want to have a view for each category -- this should be dynamic.
resources :categories do
resources :things
end
No! Don't create redundant views like that.
Put the following code in your Category
model, and any other model you wish to have descriptive URLs:
def to_param
return "#{id} #{name}".parameterize
end
Assuming name
is an attribute of Category
, this will create unique URLs containing the category name. If you know that name will definitely be unique, you can replace the return line with just name.parameterize
.
精彩评论