Reputation: 208
i am trying to render this partial of the association belongs_to and has_many
i.e
my model is as thus
activity Model
class Activity < ActiveRecord::Base
has_many :talks
end
talk model
class Talk < ActiveRecord::Base
belongs :activity
end
in my talk controller i have
@activities = Activity.where(user_id: [current_user.friend_ids, current_user])
@talks = Talk.find(:all, :order => "created_at DESC")
and in view i have
<% activity.talks.each do |c| %>
<div class="media">
<a class="pull-left" href="#">
<%= image_tag(c.user.image.url(:tiny),:style=> "width: 100%;")%>
</a>
<div class="media-body">
<strong><%= c.user.username %></strong> <%= c.details %><br>
<small><span class="muted"><%="#{time_ago_in_words(c.created_at)} ago "%></span></small>
</div>
</div>
<% end %>
this displays all the talk for each activity
how do i create a partial of <% activity.talks.each do |c| %>
Upvotes: 0
Views: 73
Reputation: 4102
Create a partial in
app/views/talks/_talk.html.erb
and call
<%= render activity.talks %>
This will render one _talk.html.erb
partial for each talk in the activity.talks
collection, which will have access to a talk
variable.
Furthermore, you can optimize the code by preventing N + 1 queries. In your controller,
@activities = Activity.includes(:talks).where(user_id: [current_user.friend_ids, current_user])
Notice the includes(:talks)
. Read more about eager loading in the docs linked above.
Upvotes: 1