0

我正在使用 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::ArticleAssociationsControllerArticles::UserAssociationsController#showparams.

是否可以?

4

1 回答 1

0

您不仅可以修改参数,还可以更改要查找的类。

@users_article_association = Users::ArticleAssociation.find(params[:user_id])
# and
@users_article_association = Articles::UserAssociation.find(params[:article_id])

它们完全不同。我建议你处理这些差异,然后将真正的公共代码提取到另一个方法中,并从双方调用。

于 2012-07-13T13:25:05.457 回答