简体   繁体   中英

Entries of all users show regardless of who has logged in

I'm working on my first rails project. Currently, I have a page that should only show the entries that were added by the logged in user.

Here is what the page looks like. Most of the entries at the top are random just to make sure it was accepting from the form.

I created another account and realized that I could still see entries from the other account.

Here: https://share.getcloudapp.com/yAuv4k7k

Currently, I have the controller set as

class PersonsController < ApplicationController

  def index
    @persons = Person.all
  end

  def show
    @person = Person.find(params[:id])
  end

end

I looked around and suspect that'll have to do something like this but I'm not sure where to put the code.

I Tried the following:

before_filter :authenticate_user!, only: [:persons, :comicbooks]

Also, For collecting the posts of a specific user, I tried this:

@persons = current_user.persons

Here is the error I get: https://share.getcloudapp.com/z8uXw1y6

Here is the persons_controller.rb: https://share.getcloudapp.com/JruWwndN

-- All help appreciated. Thanks.

The first thing, before_filter:authenticate_user,: only: [,persons: :comicbooks] is not working. right syntax is before_filter:authenticate_user,: only: [:index] or before_filter:authenticate_user,: only: [:index] or just before_filter:authenticate_user! . It mean authenticate_user! method will be excute before execute index , show methods.

The second, if you want to collect the posts of a specific user, you need to ensure that you have been declared has_many:posts in user model. Then you can use current_user.posts to collect all post of specific user.

From the pictures you shared you have a code in your controller with an instance variable:

@person = current_user.Person

This is wrong as Person does not belong to a user but rather current_user.person .

current_user is autoloaded globally so the authenticate_user! callback has no effect on it. Now to get all the posts for a specific, logged in user, you can use:

@posts = current_user.persons

The code you have on the last line of your question should work but I don't think it's the same as you have in the error screenshot you posted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM