How to display which user created the post?

Viewed 67

Trying to learn ruby on rails by creating a reddit clone.

So now I'm trying display the username of the user who created the post, but I'm only getting it displayed as u/username everywhere.

Also when I try to click on u/username to see if I can get data about user by going to his page, all I'm getting is an error saying:

undefined method `username' for nil:NilClass

This is my partial _list class that displays data about post:

<% posts.each do |post| %>
   <%= link_to post.community.name %> | Posted by <%= link_to post.account.username, profile_path(:username) %> <%= time_ago_in_words post.created_at%> ago. </p> </small>
   <%= link_to  post.title, community_post_path(post.community_id, post) %> 
   <%= truncate post.body, length: 200 %>
<% end %>

profile.html.erb just to display username for now:

<%= @profile.username %>

account.rb:

class Account < ApplicationRecord

  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable
  has_many :posts
  has_many :communities
  
  validates_presence_of  :username


end

public_controller:

class PublicController < ApplicationController

    def index
        @communities = Community.all.limit(5)
        @posts = Post.order(id: :desc).limit(20)
    end

    def profile
        @profile = Account.find_by_username params[:username]
    end
    
end

post.rb:

class Post < ApplicationRecord
    belongs_to :account
    belongs_to :community
  
    validates_presence_of :title, :body, :account_id, :community_id
end

and routes.rb:

Rails.application.routes.draw do
  devise_for :accounts
  get "u/:username" => "public#profile", as: :profile
  
  resources :communities do
    resources :posts
  end

  root to: "public#index"
end

Full repo here

0 Answers
Related