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:
render object
syntax but specify a different partial name; orA 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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With