I'm new to rails and I'm having problems figuring out how to limit the ability to for 1 user to see the records that another user creates. I have Users and Children and I want to make it so a User with user_id of 1 who creates children_id of 8,9 can only see children 8,9. I also want to make it so User_id 2 cannot see user_id 1 or children 8 and 9. I am using restful_authentication.
The simplest thing to do is create a relationship between the record and the user. If you object/record was product then:
class Product belongs_to :user end
class User has_many :products end
then in your Product controller always access products via the user:
def index current_user.products end
def new current_user.products.build end
def create current_user.products.build(params[:products]) end
etc....
HTH, Nicholas
Nick,
WOW! Thanks for the quick reply. I have created the relationship and I will change my controllers to reflect your suggestion. Thanks a bunch for the help.
One thing. I looked at the example you send and was wondering if this will prevent other users from viewing the products created by other users? That is what I am trying to do. I will test you code ASAP.
To clarify...
def create current_user.products.build(params[:products]) end
should have been
def create current_user.products.build(params[:products]) .... # etc end
Yes it will, just use the scope when finding a record. Continuing from
my previous example:
def show @product = current_user.products.find(params[:id]) end
Thanks so much for the help. This worked perfectly. Sorry for the late response.