我有以下关系路线:
resources :courses, only: [:index, :show] do
resources :enrols, only: [:new, :create]
resources :lectures, only: [:show]
end
resources :code_casts, :path => 'casts', :as => 'casts', only: [:index, :show]
resources :blogs, :path => 'blog', :as => 'blog', only: [:index, :show] do
resources :blog_votes, only: [:create, :destroy]
end
我想在课程,讲座,code_casts和博客中进行多态评论。
问题是讲座当然有父母,所以路由将是course/course_id/lecture/id
,博客路径将blog/id
,其中评论将有不同的显示页面。
答案 0 :(得分:0)
如果我正确理解了问题,那么深层嵌套资源就没什么特别之处了。所以你可能需要这样的东西
# routes.rb
concern :commentable do
resources :comments
end
resources :courses, only: [:index, :show] do
resources :enrols, only: [:new, :create]
resources :lectures, only: [:show], concerns: [:commentable]
end
resources :code_casts, :path => 'casts', :as => 'casts', only: [:index, :show]
resources :blogs, :path => 'blog', :as => 'blog', only: [:index, :show], concerns: [:commentable] do
resources :blog_votes, only: [:create, :destroy]
end
这将为讲座和博客创建嵌套的comments
资源。
您需要区分注释控制器中的路径
# comments_controller
def create
Comment.create(commentable: commentable, other_params...) # assuming you have `commentable` polymorphic belongs_to
end
# a little more ugly than Ryan suggests
def commentable
if request.path.include?('blog') # be careful. any path with 'blog' in it will match
Blog.find(params[:id])
elsif params[:course_id] && request.path.include?('lecture')
Course.find(params[:course_id).leactures.find(params[:id]) # assuming Course has_many lectures
else
fail 'unnable to determine commentable type'
end
end
所有魔法'是一个可评论的方法,您可以在其中检查路径并确定要选择的可评论对象。我使用类似的方法,但这个确切的代码是由内存编写的,没有测试。希望你有这个想法。