Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I only show items that belong to a certain user (using restful_authentication)?

I have a web application with users and their documents. Each user can have many documents:

user.rb:

has_many :documents

document.rb:

belongs_to :user

document_controller.rb:

def index
    @documents = Document.find(:all)
end

I am using the restful_authentication plugin. Here is my question: How do I get the controller to only show documents that belongs to each user? Right now it shows all the documents for all the users.

I am using the latest version of Rails.

like image 538
David Smit Avatar asked Dec 06 '22 07:12

David Smit


1 Answers

You set a relationship in your User class to your Document class. This will automatically add a method to your User objects that returns a list of all documents related to a particular user:

def index
  @documents = @current_user.documents
end

See the documentation for other automatically added methods.

like image 98
sock Avatar answered Jan 05 '23 01:01

sock