对两个不同文件夹中的两个控制器使用相同的部分

时间:2015-02-05 16:15:34

标签: ruby-on-rails

我有两个像这样的控制器:

应用程序/控制器/ collection_controller.rb:

class CollectionController < ApplicationController
    def create
      @collection = Collection.new(name: params[:name])
      @collection.save!
      render @collection
    end
end

一个继承的类:

应用程序/控制器/企业/ collection_controller.rb:

class Enterprise::CollectionController < ::CollectionController
    def create
      @collection = Collection.new(name: params[:name])
      @collection.company = Company.find(params[:company])
      @collection.save!
      render @collection
    end
end

我有两个部分:

应用程序/视图/集合/ _collection.json.jbuilder:

json.extract! collection, :title, :description
json.users do
    json.partial! collection.user
end

应用程序/视图/集合/ _user.json.jbuilder:

json.extract! user, :name, :surname

问题是:

当我加载Enterprise::CollectionController#create时,我得到missing template app/views/enterprise/collections/_collection ...

我希望Enterprise :: CollectionController使用app/view/collections/_collection.json.jbuilder而不是app/view/enterprise/collections/_collection.json.jbuilder

我尝试过这样的事情:

render @collection, partial: 'collections/collection', but I receive:

但我收到了:

missing template for ... app/views/enterprise/users/_user ...

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

将渲染部分更改为

render @collection, partial: 'collections/collection'

您没有收到collection部分错误。你得到user部分错误。您将不得不改变将用户局部渲染为

的方式
json.partial! "collections/user", user: collection.user

<强>更新

你可以尝试append_view_path。所以基本上你会附加到默认的搜索位置

class Enterprise::CollectionController < ::CollectionController
   before_filter :append_view_paths
   def append_view_paths
      append_view_path "app/views/collections"
   end
end

因此rails会按顺序搜索app/views/enterprise/collections, app/views/shared, app/views/collections

如果您希望rails prepend_view_path首先搜索

,也可以使用app/views/collections PS:我还没有测试过这个。

相关问题