路线关注和多态模型:如何共享控制器和视图? [英] Route concern and polymorphic model: how to share controller and views?
问题描述
给出路线:
Example::Application.routes.draw do
concern :commentable do
resources :comments
end
resources :articles, concerns: :commentable
resources :forums do
resources :forum_topics, concerns: :commentable
end
end
和模型:
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true
end
当我编辑或添加评论时,我需要回到"commentable"对象.但是,我有以下问题:
When I edit or add a comment, I need to go back to the "commentable" object. I have the following issues, though:
1)comments_controller.rb
中的redirect_to
取决于父对象
1) The redirect_to
in the comments_controller.rb
would be different depending on the parent object
2)视图上的引用也会有所不同
2) The references on the views would differ as well
= simple_form_for comment do |form|
是否存在一种实用的方法来共享此comment
资源的视图和控制器?
Is there a practical way to share views and controllers for this comment
resource?
推荐答案
您可以在before过滤器中找到父对象,如下所示:
You can find the parent in a before filter like this:
comments_controller.rb
before_filter: find_parent
def find_parent
params.each do |name, value|
if name =~ /(.+)_id$/
@parent = $1.classify.constantize.find(value)
end
end
end
现在,根据父类型,您可以重定向或执行任何您想做的事情.
Now you can redirect or do whatever you please depending on the parent type.
例如在视图中:
= simple_form_for [@parent, comment] do |form|
或者在控制器中
comments_controller.rb
redirect_to @parent # redirect to the show page of the commentable.
这篇关于路线关注和多态模型:如何共享控制器和视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!