【问题标题】:Is it possible to "map" a controller action to another controller action but changing some parameter?是否可以将控制器动作“映射”到另一个控制器动作但更改某些参数?
【发布时间】: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::ArticleAssociationsControllerArticles::UserAssociationsController#show 之间的唯一变化是params

有可能吗?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 rails-activerecord dry rails-routing


    【解决方案1】:

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

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

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

    【讨论】:

    • 实际上,Users::ArticleAssociationArticles::UserAssociationsame 因为类继承。但是,您的解决方案可能是正确的。
    • 你的find 方法如何知道它得到什么样的id?您只需向其传递一个数字,如果两个类相同,则无论您要查找什么,该 id 在每种情况下都用作用户 id 或文章 id。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多