开发者

Rails authentication gift list for each user?

开发者 https://www.devze.com 2023-01-20 13:49 出处:网络
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 lo

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 ha开发者_如何转开发s 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
end

gift model

class Gift < ActiveRecord::Base
belongs_to :person
end

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?

Thanks,

Danny

UPDATE: The app so far is on Heroku and Github.

http://giftapp.heroku.com/

http://github.com/dannyweb/GiftApp


Would that work, or am I missing something?

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)
end

You need something along the lines of:

def index
  @people = current_user.people
end

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
  else
    render :action => 'new'
  end
end
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号