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路徑相關/articles/:article_id/user路徑控制器動作HTTP請求。

:我想提出的是,爲了乾的(不要重複自己)的代碼,但是,正如前面所說,Users::ArticleAssociationsControllerArticles::UserAssociationsController#show之間改變的唯一事情是params

可能嗎?

回答

0

您不僅可以修改參數,還可以更改要查找的類。

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

它們完全不同。我建議你處理這些差異,然後將真正的通用代碼提取到另一種方法,並從雙方進行調用。

+0

實際上,'Users :: ArticleAssociation'和'Articles :: UserAssociation'是自從類繼承之後的* *。但是,您的解決方案可能是正確的。 – Backo 2012-07-13 13:40:22

+0

你的'find'方法怎麼知道它得到了什麼樣的id?你只傳遞一個數字給它,如果這兩個類是相同的,那麼無論你在尋找什麼,在任何情況下,id都可以用作用戶ID或文章ID。 – Matzi 2012-07-14 13:01:48

相關問題