Ask A Question

Notifications

You’re not receiving notifications from this thread.

Display Posts on Homepage

MikeLangford asked in Rails

I am building a social app and I want to display the content of the /posts page (index.html.erb) on the homepage if a user is logged in.

The code below works just fine on the /posts page to display the list of posts. However, when I try to use it on the Home page it throws the error "undefined method `each' for nil:NilClass"

Any suggestions on how to adjust the <% @posts.each do |post| %> so it works on the Home page? Or, should I direct users to the Posts page with a <% if user_signed_in? %> as a replacement for the home page?

<% @posts.each do |post| %>





  • <%= post.created_at.strftime("%b %e, %Y") %>
    <%= post.user.name.full %>


    <%= post.content %>


    <%= link_to 'Show', post %>
    <% if post.user == current_user %>
    <%= link_to 'Edit', edit_post_path(post) %>
    <%= link_to 'Delete', post, method: :delete, data: { confirm: 'Are you sure?' } %>
    <% end %>
    <% end %>
  • Reply

    Hey Mike,

    If you want to list posts on the homepage, you just need to query for them in your homepage's controller action.

    def index
      @posts = current_user.posts if user_signed_in?
    end
    ```
    
    Also if you use Devise, you can actually change the root when a user is logged in which I find to be the most easy option for modifying the homepage when a user is logged in. That way you can point it to any controller action and it'll be separated out nicely.
    
    ```
    # config/routes.rb
    authenticated :user do
      root to: "posts#index"
    end
    
    root to: "homepage#show"
    ```
    
    Reply

    You rock Chris! Thank you.

    The second solution of routing to "posts#index" was exactly what I had in mind.

    Reply
    Join the discussion
    Create an account Log in

    Want to stay up-to-date with Ruby on Rails?

    Join 78,890+ developers who get early access to new tutorials, screencasts, articles, and more.

      We care about the protection of your data. Read our Privacy Policy.

      Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more.

      © 2023 GoRails, LLC. All rights reserved.