【问题标题】:Rails authentication gift list for each user?每个用户的 Rails 身份验证礼物清单?
【发布时间】:2010-10-21 10:01:59
【问题描述】:

我正在尝试掌握 Rails 中的身份验证基础知识。首先,我使用了 Ryan Bates 的 nifty_authentication 生成器。它帮助我了解用户登录等的基本选项。

我有一个简单的应用程序,在数据库中有一个人和礼物表。这个想法是,每个用户创建一个人员列表,然后为每个人分配可能的礼物。

所以从结构上看:

person belongs to user
gift belongs to person

所以我的模型设置如下。

人物模型

class Person < ActiveRecord::Base
has_many :gifts
end

礼品模型

class Gift < ActiveRecord::Base
belongs_to :person
end

用户模型

currently doesn't contain any belongs_to has_many etc.

如何确保每个用户都有自己的人员列表。因此,一个用户无法看到其他用户的人员或礼物列表。

我是否只需将以下内容添加到用户模型中?

has_many :people

还有以下的人物模型?

belongs_to :user

这会起作用吗,还是我错过了什么?

谢谢,

丹尼

更新: 该应用目前在 Heroku 和 Github 上。

http://giftapp.heroku.com/

http://github.com/dannyweb/GiftApp

【问题讨论】:

    标签: ruby-on-rails authentication model relationship


    【解决方案1】:

    这行得通吗,还是我错过了 什么?

    非常简短的回答:是的,这行得通;不,你并没有错过什么。


    我看了你的代码。

    代替:

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

    你需要一些类似的东西:

    def index
      @people = current_user.people
    end
    

    其中current_user 是引用登录用户的User 对象。

    create 方法中,您需要将新创建的人员分配给 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
    

    【讨论】:

    • 好的,谢谢。我已经完成了我建议的更改,并在名为 user_id 的人员表中添加了一个列。一切正常,但是,每个人都可以看到所有人。它仍然是一个很大的公共列表。
    • 在显示人员列表时,您需要current_user.people 之类的东西,而不是Person.all。我不知道 nifty_authentication 生成器,但它应该为登录用户提供一个对象。
    • 在视图或人员控制器中?
    • 好的,我把它改成了@people = current_user.people。该应用程序仍然有效,我可以创建新人,但在我离开显示人员页面后他们没有出现。一旦我点击返回主页,就没有列出任何人。我是否还需要更改显示视图?
    • 好的,我想通了。您必须在 PeopleController 顶部添加before_filter :login_required。在class PeopleController &lt; ApplicationController 之后的第二行。
    猜你喜欢
    • 2016-04-12
    • 2014-09-02
    • 2017-04-21
    • 1970-01-01
    • 1970-01-01
    • 2018-04-15
    • 2011-02-21
    • 2016-03-19
    • 2018-12-23
    相关资源
    最近更新 更多