Rails:如何路由非相关资源?

时间:2022-10-27 17:14:47

I have four models:

我有四种模式:

class User < ActiveRecord::Base
  has_many :posts
end

class Category < ActiveRecord::Base
  has_many :posts
end

class Post < ActiveRecord::Base
  belongs_to :user
  belongs_to :metric
  has_many :comments
end

class Comments < ActiveRecord::Base
  belongs_to :post
end

I'd like to be able to access a post within a certain category for a specific user. For example:

我希望能够为特定的用户访问特定类别的帖子。例如:

http://domain.com/users/1/categories/1/posts

Also I want to see a list of all categories if I visit:

如果我访问的话,我还想看看所有类别的列表:

http://domain.com/users/1/categories/

Since categories are fixed and the same for all users, User and Category don't have a direct association. Because of this, I'm not quite sure how to configure the routes.rb file to access posts within a category for a user. I'd appreciate any suggestions. Thanks!

由于类别是固定的,对所有用户来说都是一样的,用户和类别没有直接的关联。因此,我不太确定如何配置路由。rb文件,用于访问用户类别内的文章。任何建议,我将不胜感激。谢谢!

1 个解决方案

#1


1  

You could use nested resources to do that like :

您可以使用嵌套资源来完成如下操作:

resources :users do
  resources :categories
end

For more : http://guides.rubyonrails.org/routing.html#nested-resources

更多信息:http://guides.rubyonrails.org/routing.html nested-resources

#1


1  

You could use nested resources to do that like :

您可以使用嵌套资源来完成如下操作:

resources :users do
  resources :categories
end

For more : http://guides.rubyonrails.org/routing.html#nested-resources

更多信息:http://guides.rubyonrails.org/routing.html nested-resources