我正在使用Ruby on Rails 3.2.2,我想知道是否可以将控制器动作“映射”到另一个控制器动作但是改变一些参数。也就是说,我有以下模型和控制器:
# File system:
# /app/models/articles/user_association.rb
# /app/models/users/article_association.rb
# /app/controllers/users/article_associations_controller.rb
# /app/controllers/articles/user_associations_controller.rb
# /app/models/articles/user_association.rb
class Articles::UserAssociation < ActiveRecord::Base
...
end
# /app/models/users/article_association.rb
class Users::ArticleAssociation < Articles::UserAssociation # Note inheritance
#none
end
# /app/controllers/users/article_associations_controller.rb
class Articles::UserAssociationsController < ApplicationController
def show
@articles_user_association = Articles::UserAssociation.find(params[:article_id])
...
end
def edit
@articles_user_association = Articles::UserAssociation.find(params[:article_id])
...
end
...
end
# /app/controllers/articles/user_associations_controller.rb
class Users::ArticleAssociationsController < ApplicationController
def show
# It is the same as the Articles::UserAssociationsController#show
# controller action; the only thing that changes compared to
# Articles::UserAssociationsController#show is the usage of
# 'params[:user_id]' instead of 'params[:article_id]'.
@users_article_association = Users::ArticleAssociation.find(params[:user_id])
...
end
def edit
# It is the same as the Articles::UserAssociationsController#edit
# controller action; the only thing that changes compared to
# Articles::UserAssociationsController#edit is the usage of
# 'params[:article_id]' instead of 'params[:user_id]'.
@users_article_association = Users::ArticleAssociation.find(params[:user_id])
...
end
...
end
因此,我想处理指向/users/:user_id/article
路径的HTTP请求,作为与/articles/:article_id/user
路径相关的控制器操作。
注意:我想这样做是为了干(不要重复自己)代码,但是,如前所述,Users::ArticleAssociationsController
和{之间唯一的变化{1}}是Articles::UserAssociationsController#show
。
有可能吗?
答案 0 :(得分:0)
您不仅可以修改参数,还可以更改要查找的类。
@users_article_association = Users::ArticleAssociation.find(params[:user_id])
# and
@users_article_association = Articles::UserAssociation.find(params[:article_id])
他们完全不同。我建议你处理这些差异,然后将真正的公共代码提取到另一个方法,并从双方调用它。