Rails: How do I route unassociated resources?

南笙酒味 提交于 2019-12-11 15:25:38

问题


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!


回答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



来源:https://stackoverflow.com/questions/5760162/rails-how-do-i-route-unassociated-resources

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!