How to refactor this code? I write on Sinatra I need to separate into a separate file
<div class="row">
<div class="col-xs-3">
<% @user.posts.each do |post| %>
<a href="/posts/<%= post.id %>"><%= post.title %></a><br>
<p><%= post.body %></p>
<% unless post.comment.blank? %>
<% post.comment.each do |comment| %>
<p><%= comment.body %></p>
<% unless comment.comment.blank? %>
<% comment.comment.each do |comment2| %>
<p><%= comment2.body %></p>
<% unless comment2.comment.blank? %>
<% comment2.comment.each do |comment3| %>
<p><%= comment3.body %></p>
<% end %>
<% end %>
<% end %>
<% end %>
<% end %>
<% end %>
<% end %>
</div>
</div>
my model looped comment
def up
create_table :comments do |t|
t.string :body
t.integer :post_id
t.integer :comment_id
t.timestamps
end
end
This is my migration model comment
From the documentation:
Use it as follows to render the mypartial.haml(1) or the admin/mypartial.haml(2) partials, or with a collection (3) & (4):
<%= partial(:mypartial) %> <!--(1)--> <%= partial(:'admin/mypartial') %> <!--(2)--> <%= partial(:object, :collection => @objects) %> <!--(3)--> <%= partial(:'admin/object', :collection => @objects) %> <!--(4)-->
In (1) & (2), the partial will be rendered plain from their files, with no local variables (specify them with a hash passed into :locals). In (3) & (4), the partials will be rendered, populating the local variable object with each of the objects from the collection.
So your code should be:
<div class="row">
<div class="col-xs-3">
<% @user.posts.each do |post| %>
<a href="/posts/<%= post.id %>"><%= post.title %></a><br>
<p><%= post.body %></p>
<%= partial(:comment, :collection => post.comment) %>
<% end %>
</div>
</div>
with the new file comment.erb
:
<p><%= comment.body %></p>
<%= partial(:comment, :collection => comment.comment) %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With