If you wrote one piece of code many times in your View, you should consider using a partial instead of writing that code again. Partial templates - usually just called "partials" - is a mechanism that reuse your code, that what Rails always said: "Don't repeat yourself".
If you are new in Rails, you should already write the new and edit view, like following:
All most the same, huh? Rails partial provied the abliity that reuse this code. You could move the same code to another view file, like:
Then, call it in new and edit view, such as:
The view pages are rendered as same as before, amazing.
You should note that the partial filename should start with '_' and when you call it, '_' is not need.
Partial provide more, you could pass local variables into partial, making them even more powerful and flexible:
that would replace the
post variable in
Another magic is if you render a partial using a plural name, Rails would automatic find the single partial view and render it.
Rails would find
_post.html.erb to render.
There are more fun using partial, find it in Rails Guide.