DEV Community

Saral Karki
Saral Karki

Posted on

Figuring it out

Towards the end of the day, I finally figured out what it was I was doing wrong, or should I say, what I was not doing at all. So this was what I was struggling with yesterday.

What did I do differently today?

First off, I was trying to authenticate via the username yesterday. In my head, I was thinking I would do something like, <%= if user.username == post.username , then it would give the user the ability to delete or edit their post.

However, following a tutorial by Andy Leverenz where he teaches how to build a twitter like app, I figured out what it was I required to do. Instead of trying to validate by the username, what I could do instead was validated by the user.id. This user id would link the post database with the user database.

How did I go about it?

First off, I added a user_id field in my post model via rails generate migration
add_userid_to_post userid: integer
. Then after rails db: migrate I was able to get the field user.id in my post database.

After this, I made modifications to my post.rb and user.rb files in the model folder.

Post.rb

class Post < ApplicationRecord
    belongs_to :user
end

User.rb

class User < ApplicationRecord
  has_secure_password
  validates  :username, :email, uniqueness: true, presence: true

  has_many :post
end

Now, I made a few changes to the post controller. Mainly in the new and create method.

def new
        @post = current_user.post.build

    end

    def create
        post = current_user.post.build(post_params)
        if post.save
            redirect_to post_path(post)           
        else
            flash[:error] =   "could not save"
            redirect_to new_post_path          
        end
    end

What the new method now did was built the post by getting the current_user and created the post.

Once this was done, now I had a post_id in every post. This meant that whichever user wrote the post(or was logged in the session at the time) would be attributed to the post.

Armed with this, I made changes to file

<%  if session[:user_id] == post[:user_id]%>
            <td><%= link_to 'Edit', edit_post_path(post) %></td>
             <td><%= link_to 'Delete', destroy_post_path(post),
              method: :delete,
              data: { confirm: 'Are you sure?' }%></td>
            <% end %>

Voila! it worked. The condition if the session[:user_id] == post[:user_id] only then was the user able to destroy or edit the document.

I intend to deploy the app on heroku tomorrow after making some layout changes. A big thank you to

for getting me through this.

Also, here's a link to the repo comments, criticism and feedback of any kind are welcome. :)

Top comments (1)

Collapse
 
justalever profile image
Andy Leverenz

Thanks for the mention!🙌