有没有一种干净的方法来在嵌套控制器中找到对象的多态实例?

时间:2017-06-30 14:33:28

标签: ruby-on-rails

我使用具有多态关系的模型使用嵌套控制器。我想知道是否有一种干净的方法可以找到@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 个答案:

答案 0 :(得分:1)

您可以尝试:

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

同样在路线中你可以通过以下方式缩短时间:

resources :users, :products do
  resources :comments
end