开发者

Scoping Rails Routes to Specific Properties of a Model

开发者 https://www.devze.com 2023-04-08 04:12 出处:网络
So I have a resource type Post, that can be associated with a resource of type Category.I have th开发者_运维技巧e following in my routes.rb file:

So I have a resource type Post, that can be associated with a resource of type Category. I have th开发者_运维技巧e following in my routes.rb file:

resources "code", :controller => :posts, :as => :code
resources "sports", :controller => :posts, :as => :sports
resources "gaming", :controller => :posts, :as => :gaming
resources "personal", :controller => :posts, :as => :personal

So this gives me the desired effect of accessing particular categories through a friendly URL, like http://host.domain/sports, and that will collect all the posts with a category of sports. However, I'm not entirely sure how to scope those resources to be particular to individual categories. I suppose I could do something like:

match ":category_name", :to => posts#index

But that is problematic because it will catch everything.

So I guess in summary what I'm looking for is to maintain friendly URLs (of the exact structure I've specified) for accessing posts with a particular category. Thoughts?


You have a number of resources, should be accessible per each own url. Four of resources are the same type and can be determine as posts. It's ok to provide their functionality by one controller and it's easy to detect the current path, then parse and add number of active record scopes.

But let's look a little bit deeper. You have the same type of data, probably with same attributes, so the common pattern is "Single Table Inheritance", it equal the one table and more models, the column "type" differs the models.

Controllers are provide interface between user interaction and data flow, so I'd suggest you to use independent controller per each resource. It's a general practice. If you don't like to type more typical code, use Resourceful Controller plugin or so.

Then you can have the structure:

#routes
resources :code, sports, :gaming, :personal

# STI parent and children models
  model Post < ActiveRecord::Base
  model Sport < Post
  ...
0

精彩评论

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

关注公众号