【发布时间】:2012-07-13 09:45:18
【问题描述】:
我正在使用 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 路径相关的控制器操作来处理。
注意:我想这样做是为了 DRY(不要重复自己)代码,但是,如前所述,Users::ArticleAssociationsController 和 Articles::UserAssociationsController#show 之间的唯一变化是params。
有可能吗?
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 rails-activerecord dry rails-routing