views:

133

answers:

3

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.

+5  A: 

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.

sock
+1  A: 

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

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