Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the lookup paths for Rails partial based on model

I currently have some template code like so:

render partial: 'reference', locals: { object: object }

Rails looks for the partial _reference.html.erb in app/views/application/ and app/views/controller_name/.

However, this view is in a standalone controller, not related to the object being rendered, so it doesn’t look in the object’s view directory app/views/object. I can’t use the standard render object syntax and have Rails automagically figure out the partial path because I don’t want to render the object/object partial, but the object/reference partial.

How can I get round this?

I’m thinking either:

  • Some way to use the render object syntax but specify a different partial name; or
  • A helper function to find the partial using a different approach, used something like:

    render partial: find_partial('reference', object), locals: { object: object }
    

What I’ve tried

I tried to get the second approach working using:

def find_partial(name, object)
  lookup_context.find name, [object.class.model_name.plural, 'application'], true
end

This is very close to doing what I want, i.e. it finds the correct partial, and falls back to the generic application/reference if there isn’t one. However, it finds the actual ActionView::Template, and render is expecting a string and not the actual template object. Perhaps there’s a way to get the correct string out? Or to render an actual template?

like image 565
Leo Avatar asked Aug 31 '25 01:08

Leo


1 Answers

You can override the to_partial_path method in your model, this method is what gets called by render to determine which partial path to render for this model.

For example in your Model.rb

def to_partial_path
  "references/#{kind}"
end

Reference: http://cookieshq.co.uk/posts/rails-tips-to-partial-path/ http://apidock.com/rails/ActiveModel/Conversion/to_partial_path

like image 110
bigsolom Avatar answered Sep 02 '25 15:09

bigsolom