David Smit
David Smit

Reputation: 111

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.

Upvotes: 4

Views: 4537

Answers (4)

Lacloake
Lacloake

Reputation: 65

Try this:

def index
    @documents = Document.where(:user_id => current_user.id)
end

Upvotes: 4

JasonOng
JasonOng

Reputation: 3278

def index
  @documents = Document.find(:all, :conditions => {:user_id => session[:user_id]})
end

Upvotes: 3

srboisvert
srboisvert

Reputation: 12759

Take a look here in the rails API in the Association Join Models section.

However be aware Restful authentication won't control access in order to limit the users to only their own records particularly with restful routes. They can still view other users' records by entering values in the urls once they are logged in.

For that you might want to look into Restful ACL

Upvotes: 2

sock
sock

Reputation: 1054

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.

Upvotes: 7

Related Questions