【问题标题】:Can "belongs_to" be defined more than once in Active_Record?是否可以在 Active_Record 中多次定义“belongs_to”?
【发布时间】:2012-07-02 20:29:04
【问题描述】:

我正在尝试为镇上的一家公司编写数据库。我使用 Devise 进行身份验证,使用 Forem 进行网站论坛。我决定只为 Devise 身份验证创建一个类“Account”,它将对站点有多种不同的访问类型。

大部分用户将只是客户,他们按路线(不是 Rails 路线、街道路线)隔离。所以我决定让他们有自己的个人资料模型。

我想这样做 - 个人资料与帐户和路由相关联。 (路由命名为 gmr_routes)

这段代码是正确的方法吗?我找到的文档并没有告诉我我不能,但我只是想确定......

    class Profile < ActiveRecord::Base
      attr_accessible :first_name, :last_name, :phone_number, :street_address
        belongs_to :account
        belongs_to :gmr_route
    end

Account 与 Profile 有 has_one 关系,gmr_route 有 has_many。

是这样吗?

布莱恩

【问题讨论】:

    标签: ruby-on-rails-3 database-design activerecord orm forums


    【解决方案1】:

    是的,这是完全可以接受的。您需要记住在任何具有belongs_to 的模型上包含外键ID。

    因此,在您描述的情况下,您将在迁移中包含 account_id:integergmr_route_id:integer,并将它们包含在模型中的 attr_accessible 调用中

    【讨论】:

      猜你喜欢
      • 2012-02-02
      • 1970-01-01
      • 2013-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多