简体   繁体   English

Rails上嵌套资源和简单资源红宝石中的多态注释4

[英]Polymorphic Comments in both nested resource and simple resource ruby on rails 4

I have following relationship routes: 我有以下关系路线:

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

I want polymorphic comments in courses, lectures, code_casts and blog. 我想要课程,讲座,code_casts和博客中的多态注释。

Problem is lecture has a parent of course so route will be course/course_id/lecture/id and blog path will blog/id where comments will have different show pages. 问题是,讲座是课程的父项,因此路线将是course/course_id/lecture/id ,博客路径将是blog/id ,其中评论将具有不同的显示页面。

If I understand the problem correctly, there is nothing special about deeply nested resources. 如果我正确理解问题,则深层嵌套资源没有什么特别的。 So you might need something like this 所以你可能需要这样的东西

# 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

This will create nested comments resources for lectures and blogs. 这将为讲座和博客创建嵌套的comments资源。 Than you need to differentiate the path in a comments controller 比您需要在注释控制器中区分路径

# 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

All 'magic' is in commentable method, where youare checking the path and determine which commentable object to pick. 所有“魔术”都是可注释的方法,您可以在其中检查路径并确定选择哪个可注释的对象。 I use similar approach, but this exact code is written by memory without testing. 我使用类似的方法,但是此确切代码是由内存编写的,未经测试。 Hopefully you've got the idea. 希望你有这个主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM