Rails authentication gift list for each user? – Education Career Blog

I am trying to get to grips with the basics of authentication in Rails. To start with I have used the nifty_authentication generator by Ryan Bates. It’s helping me learn the basic options for user logins etc.

I have a simple application the has a person and gift table in the database. The idea is, each user creates a list of people and then assigned possible gifts to each of those people.

So from a structural point of view:

person belongs to user
gift belongs to person

So I have the models set up as follows.

person model

class Person < ActiveRecord::Base
has_many :gifts

gift model

class Gift < ActiveRecord::Base
belongs_to :person

user model

currently doesn't contain any belongs_to has_many etc.

How do I go about making sure each user has their own list of people. So one user cannot see another users list of people or gifts.

Would I simply add the following to the user model?

has_many :people

and the following to the person model?

belongs_to :user

Would that work, or am I missing something?



The app so far is on Heroku and Github.




Would that work, or am I missing

Very short answer: yes that would work; no you are not missing something.

I looked at your code.

Instead of:

def index
  @people = Person.find(:all)

You need something along the lines of:

def index
  @people = current_user.people

Where current_user is the User object that refers to the logged in user.

In the create method you will need to assign the newly created person to the current_user:

def create
  @person = Person.new(params:person)
  @person.user = current_user # This associates @person with current_user
  if @person.save
    flash:notice = "Successfully created person."
    redirect_to @person
    render :action => 'new'

Leave a Comment