1

I get an array of search results from tire, containing objects of various activemodel types, and I need to render each to a string. Currently, I am doing this with a loop over these results calling render_to_string(result) on each. This uses the default partial for that activemodel object.

However, this requires that I set the default partial for every class I want to be searchable to be the representation for search. This means that everywhere else in the code I need to explicitly render a collection (all of the same type) I need to explicitly specify to render with my general-use partial, when really that general use partial should be the default. It also raises the question of what I would do if I needed to render a different collection of various types, as it would use the same partials as the search.

What I would really like would be to be able to pass a prefix to render_to_string that would tell it to look for the default partial, but inside this directory - which would mean I can keep my search partials separate while still being able easily render the objects.

Is there a way of doing that or some other better solution?

2
  • 1
    Have you tried things like render_to_string([:search, result])? Commented Jun 25, 2012 at 8:26
  • I like the idea, but I get ':search' is not an ActiveModel-compatible object that returns a valid partial path. Commented Jun 25, 2012 at 8:59

1 Answer 1

1

I'd call:

 render_to_string :partial => 'searches/result', :collection => @results

And then within that one partial determine how the individual results should be displayed by doing:

case result.class.name
when 'Foo'
...
end

This gives me a single location for the format and display of results.

Sign up to request clarification or add additional context in comments.

4 Comments

I'll give this a try, I would prefer to do a prefix sort of thing and have separate partials but this is certainly far better than my current solution :)
Sub the stuff within the 'when' clause into seperate partials perhaps?
I guess I could build the partial name from the class name and render it using that
I wrote a partial with: = render :partial => "search_#{search_result.class.name.downcase}", :object => search_result and it worked great. Thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.