简体   繁体   中英

Use the same partials for two controllers in two different folders

I have two controllers like this:

app/controllers/collection_controller.rb:

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

And an inherited class:

app/controllers/enterprise/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

I have two partials:

app/view/collections/_collection.json.jbuilder:

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

app/view/collections/_user.json.jbuilder:

json.extract! user, :name, :surname

The problem is:

When I load Enterprise::CollectionController#create , I get missing template app/views/enterprise/collections/_collection ... .

I want Enterprise::CollectionController to use app/view/collections/_collection.json.jbuilder instead of app/view/enterprise/collections/_collection.json.jbuilder .

I tried to do something like:

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

But I receive:

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

How can I solve this?

After you changed your render partial to

render @collection, partial: 'collections/collection'

you are not getting an error for collection partial. you are getting an error for user partial. You will have to change the way you are rendering user partial to

json.partial! "collections/user", user: collection.user

Update:

you can try append_view_path . So basically you will append to the default search locations

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

So rails will search in app/views/enterprise/collections, app/views/shared, app/views/collections in order

You can also use prepend_view_path if you want rails to search in app/views/collections first

PS: I haven't tested this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM