Reputation: 953
I am trying to print parents' and children's name with indentation. But I am not sure how I can do that in the view.(haml)
I have a model with self join:(just to give you the structure, I also have other attributes etc. but I think they are irrelevant)
class Post < ActiveRecord::Base
has_many :children, :class_name => "Post"
belongs_to :parent, :class_name => "Post", :foreign_key => "post_id"
end
So it has a hierarchy and I wanna have something like this(let's assume with the attribute 'name'):
Post 1
Post 1.1
Post 1.2
Post 2
Post 2.1
Post 2.2
I am pretty new in Ruby-on-rails. So please bear with me. I would really really appreciate if I could get a quite explanatory answer.
Thank you so much in advance, J
Upvotes: 0
Views: 759
Reputation: 29599
you can use recursion. create a partial that calls itself.
# app/views/posts/_post.html.haml
= post.title
= post.content
= render partial: 'post', collection: post.children
I'm assuming that you have a posts controller which comes with a folder for it's views in app/views/posts
. You need to create a partial there called _post.html.haml
which calls
itself. The render
line tells you to render the same partial for each of the post's children.
the indentation can be handled via css.
Upvotes: 3