我正在使用 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
的Articles::UserAssociationsController#show
是params
.
是否可以?