2017-06-30 53 views
0

我正在使用具有多態關係的模型嵌套控制器。我想知道是否有一個乾淨的方式來找到@holderCommentsController#set_holder中的代碼很難看,我在想如果rails爲這個問題提供幫助。是否有一種乾淨的方法來查找嵌套控制器中對象的多態實例?

class Comment < ActiveRecord::Base 
    belongs_to :holder, polymorphic: true 
end 

class Product < ActiveRecord::Base 
    has_many :comments, as: :holder 
end 

class User < ActiveRecord::Base 
    has_many :comments, as: :holder 
end 

Dummy::Application.routes.draw do 
    resources :products do 
    resources :comments 
    end 

    resources :users do 
    resources :comments 
    end 
end 

class CommentsController < ApplicationController 
    before_action :set_holder, only: [:new, :create] 

    # code ... 

    def new 
    @comment = @holder.comments.build 
    end 

    # code ... 

    private 

    def set_holder 
    # params = {"controller"=>"comments", "action"=>"new", "user_id"=>"3"} 
    # or 
    # params = {"controller"=>"comments", "action"=>"new", "product_id"=>"3"} 
    # Is there a Rails way to set @holder? 

    type, type_id = params.find { |k,_| /_id$/ === k } 
    @holder = type.sub(/_id$/, '').classify.constantize.find(type_id) 
    end 
end 
+1

沒什麼漂亮,但檢查出https://stackoverflow.com/ questions/26318815/polymorphic-controller-and-calling-object and http://karimbutt.github.io/blog/2015/01/03/step-by-step-guide-to-polymorphic-associations-in-rails/ – dbugger

回答

1

你可以嘗試使用:

resource, id = request.path.split('/')[1, 2] 
@holder = resource.classify.constantize.find(id) 

此外,在路線,你可以把事情通過短:

resources :users, :products do 
    resources :comments 
end 
相關問題