I’m a Rails newbie, so bear with me.
I have a few places, some pages, some partials that use:
<%= link_to "delete", post, method: :delete,
data: { confirm: "You sure?" },
title: post.content %>
Would it make sense to make this a partial since it is used repeatedly, sometimes in other partials too?
Is it o.k. to put partials in partials?
I would try and limit the use of partials within other partials, since it can negatively affect view rendering speed (i.e. rendering lots of partials is super slow), but that said, I have to say, yes it is okay to use partials within other partials.
A couple things you should probably realize about this:
- It can get confusing as all hell, especially when:
- you’re passing around a lot of local variables.
- you’re rendering collections, i.e. looping over a partial with an array of some sort.
- Inferring from the fact that you’re asking this question, you probably don’t know that you’re already rendering partials within partials.
- what I mean by this, is that the layout (presumably “application.html.erb”) is really going to be your only non-partial in a view.
- Whenever you have an action rendered by a view, i.e. ‘show’, ‘new’, ‘edit’ (assuming you’re rest-ful), you should realize that the corresponding view (i.e. ‘show.html.erb’ for example) is a partial being rendered within the main layout file.
- Therefore any use of a partial that you yourself make (‘_users.html.erb’ or what have you) is actually already a ‘partial within another partial’.
Kinda feels like Inception, doesn’t it? 🙂
As for your specific example, I agree with the other answerer that you should probably just use it as a helper. And you can use it across many models so long as you abstract enough of the stuff away in the helper, like so:
def delete_link_for(polymorphic_object, method_symbol)
link_to "delete", polymorphic_object, method: :delete,
data: { confirm: "You sure?" },
title: post.send(method_symbol)
end
That way you can invoke like this:
<%= delete_link_for(@post, :content) %>
<%= delete_link_for(@user, :username) %>
etc.
I think a template is overkill for such a small smippet. I would write a helper method instead.
2