ruby-on-railsruby-on-rails-4ancestry

how display certain branch of blog?


please help solve the problem. i use gem 'ancestry'. i made simply blog. messages_helper.rb:

module MessagesHelper
  def nested_messages(messages)
    messages.map do |message, sub_messages|
      render(message) + content_tag(:div, nested_messages(sub_messages), :class => "nested_messages")
    end.join.html_safe
  end  
end

index.html.erb:

<%= nested_messages @messages.arrange(:order => :created_at) %>
<br>
<%= render 'form' %>

schema:

create_table "messages", force: :cascade do |t|
  t.text     "content"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
  t.string   "ancestry"
end

in result i output to index.html.erb tree of messages with related messages. but i need output only certain message with related messages. e.g. for message with id=3

ps: for made blog i use this tutorial: http://railscasts.com/episodes/262-trees-with-ancestry


Solution

  • Okay, I've written about this before; there are certain things which you've got to fix with the Railscast recommendations:

    1. Put it in a partial, not helper (it gives greater autonomy)
    2. You need to make sure your structure is as versatile as you need

    --

    Here's how I'd do what you're trying to achieve:

    #app/controllers/messages_controller.rb
    class MessagesController < ApplicationController
       def index
          @messages = Message.all #-> could filter this to only retrieve id=3
          #@messages = Message.find "3" #-> like this
       end
    end
    
    #app/views/messages/index.html.erb
    <% render @messages.arrange(order: :created_at) %>
    
    #app/views/messages/_message.html.erb
    # ... single message output code ... #
    <%= render message.children if message.has_children? && message.id == "3" %>
    

    You could then extrapolate the conditional functionality into a helper. If you describe your functionality more specifically, I'll be able to make a helper to define it.