在 config/routes.rb 中:
resources :posts do
resources :comments
end
resources :pictures do
resources :comments
end
我也想允许对更多的事情发表评论。
我目前正在使用 mongoid (mongmapper 与 Rails 3 还没有我想的那样兼容),并且注释是一个嵌入式资源(mongoid 还不能处理多态关系资源),这意味着我确实需要父资源才能找到注释.
有没有什么优雅的方法来处理以下一些问题:
在我的 Controller 中,我需要在找到评论之前找到父级:
if params[:post_id]
parent = Post.find(params[:post_id]
else if params[:picture_id]
parent = Picture.find(params[:picture_id]
end
如果我开始添加更多可评论的内容,这将变得困惑。
还有
url_for([comment.parent, comment])
不起作用,所以我必须在 Comment
中定义一些东西模型,但我想我还需要在 Comment
中定义一个索引路由模型以及潜在的编辑和新路线定义。随着我走得更远,我可能需要处理更多的问题。
我无法想象我是第一个尝试解决这个问题的人,是否有任何解决方案可以使这个问题更易于管理?
最佳答案
我不得不在我的应用程序中做类似的事情。我接受了我想出的东西并对其进行了一些更改,但我还没有对其进行测试,因此请谨慎使用。它并不漂亮,但它比我能想到的任何其他东西都要好。
在routes.rb中:
resources :posts, :pictures
controller :comments do
get '*path/edit' => :edit, :as => :edit_comment
get '*path' => :show, :as => :comment
# etc. The order of these is important. If #show came first, it would direct /edit to #show and simply tack on '/edit' to the path param.
end
在评论.rb:
embedded_in :commentable, :inverse_of => :comments
def to_param
[commentable.class.to_s.downcase.pluralize, commentable.id, 'comments', id].join '/'
end
在 comments_controller.rb 的前置过滤器中:
parent_type, parent_id, scrap, id = params[:path].split '/'
# Security: Make sure people can't just pass in whatever models they feel like
raise "Uh-oh!" unless %w(posts pictures).include? parent_type
@parent = parent_type.singularize.capitalize.constantize.find(parent_id)
@comment = @parent.comments.find(id)
好了,丑完了。现在您可以为您想要的任何模型添加注释,只需执行以下操作:
edit_comment_path @comment
url_for @comment
redirect_to @comment
等等。
编辑:我没有在自己的应用程序中实现任何其他路径,因为我需要的只是编辑和更新,但我想它们看起来像:
controller :comments do
get '*path/edit' => :edit, :as => :edit_comment
get '*path' => :show, :as => :comment
put '*path' => :update
delete '*path' => :destroy
end
其他 Action 会比较棘手。您可能需要执行以下操作:
get ':parent_type/:parent_id/comments' => :index, :as => :comments
post ':parent_type/:parent_id/comments' => :create
get ':parent_type/:parent_id/comments/new' => :new, :as => :new_comment
然后,您将使用 params[:parent_type] 和 params[:parent_id] 访问 Controller 中的父模型。您还需要将正确的参数传递给 url 助手:
comments_path('pictures', 7)
关于ruby-on-rails-3 - 有人对在 Rails 3 中管理多态嵌套资源有什么建议吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3681531/