Reputation: 42049
In the index file of a Rails to-do app (code from Railscast), it lists out the incomplete and complete tasks that were assigned to instance variables in the tasks controller. Notice how it calls render @incomplete_tasks and render @complete_tasks, whereas the partial is only called
_task.html.erb
It appears this one partial is used for rendering both incomplete and complete tasks. Is Rails able to ignore the first half of the instance variables (ie. @incomplete and @complete) to use the one partial for rendering both?
controller
def index
if current_user
@incomplete_tasks = current_user.tasks.where(complete: false)
@complete_tasks = current_user.tasks.where(complete: true)
end
end
Index
<% if @incomplete_tasks.empty? && @complete_tasks.empty? %>
<p>Currently no tasks. Add one above.</p>
<% else %>
<h2>Incomplete Tasks</h2>
<div class="tasks" id="incomplete_tasks">
<%= render @incomplete_tasks %>
</div>
<h2>Complete Tasks</h2>
<div class="tasks" id="complete_tasks">
<%= render @complete_tasks %>
</div>
<% end %>
_task.html.erb
<%= form_for task, remote: true do |f| %>
<%= f.check_box :complete %>
<%= f.label :complete, task.name %>
<%= link_to "(remove)", task, method: :delete, data: {confirm: "Are you sure?"}, remote: true %>
<% end %>
Upvotes: 1
Views: 422
Reputation: 17949
There is full answer on this question.
http://guides.rubyonrails.org/layouts_and_rendering.html
2.2.13 Avoiding Double Render Errors
Upvotes: 0
Reputation: 20938
Copying the answer of @ryanb, see it here : Rails: Rendering Models?
If you pass a model directly to render it will attempt to render a partial for it.
<%= render @thing %>
That is the same as.
<%= render :partial => 'things/thing', :object => @thing %>
If you pass an array of models...
<%= render @things %>
It will render the _thing
partial for each as if you did this.
<%= render :partial => 'things/thing', :collection => @things %>
Note: this requires Rails 2.3. If you have earlier versions of Rails you'll need to use the :partial option to do the same thing.
<%= render :partial => @thing %>
Upvotes: 0
Reputation: 112
So rails looks at the model objects to determine which partial to use when you use that kind of syntax. In both cases the instance variables contain tasks so rails knows to use the _task partial.
Upvotes: 2