I’m a Rails newbie…. Here’s what I’m trying to do….
I created a scaffold for notes (t.text :content, t.integer :user_id)
What I want to do now is only allow user’s to view notes that they created. ie (== user_id)
In my /app/controllers/notes_controller.rb
I have the following:
class NotesController < ApplicationController
before_filter :authenticate
before_filter :correct_user
.
.
.
.
def correct_user
@noteuserid = Note.find(:conditions=>["note.user_id=?", @noteuserid])
redirect_to(root_path) unless current_user?(@noteuserid)
end
I’m having problems understanding how to write the following line: @noteuserid = Note.find(:conditions=>[“note.user_id=?”, @noteuserid])
Any ideas?
Thanks
So, firstly you want to find the
Notebeing accessed by the user, then check whether thatNoteis valid for the user. I would try something like this (assuming that yourcurrent_user?method checks whether a given user id matches the current logged in user:Also, you may want to watch out for filtering all actions in the controller with your
correct_userfilter as actions to create a note may not have an id of a note to check against. Additionally, when you are viewing a collection of notes you will need to filter differently (e.g.Note.find(:all, :conditions => { :user_id => current_user_id })). It may be more appropriate to apply the correct logic in specific actions rather than as a generic filter.Finally, you could look at the cancan plugin which would do a lot of the hard work for you with code like this.