【问题标题】:has_one relation depending on user typehas_one 关系取决于用户类型
【发布时间】:2013-02-09 21:01:39
【问题描述】:

我正在尝试为我的用户创建不同的个人资料类型。

我有一个用户模型。

User 类型有一个Profile 相关,所以它@98​​7654323@ 但是,Page 类型有一个Page 相关,所以它@98​​7654326@

但是,我对两者都使用相同的 User 表,并且我正在设置帐户类型。

我想知道,如何根据我的用户帐户类型确定这种关系

编辑

用户模型 has_one :profile Profile belongs_to :user Page belongs_to :user 帐户类型是“User”(进入 Profile 模型)或“Page”(进入 Page 模型)。

class User < ActiveRecord::Base
  has_one :profile, :class_name => 'Here it should be either PROFILE or PAGE'
end

class Profile < ActiveRecord::Base
  belongs_to :user
end

class Page < ActiveRecord::Base
  belongs_to :user
end

我已经通过 API 阅读了一下,发现 :class_name,现在我的挑战是动态确定它。

编辑

稍微修改了页面模型和用户模型。

【问题讨论】:

  • 请发布您的模型及其关联。 “帐户类型”是指“个人资料”吗?
  • 用户模型 has_one :profile Profile belongs_to :user Page belongs_to :user 账户类型要么是“User”(进入 Profile 模型),要么是“Page”(进入 Page 模型)我已经通过API阅读了一下,发现:class_name,现在我的挑战是动态确定它。
  • 如果我理解正确,User 有一个属性account_type,它是PageUser.profile 的一个实例?
  • 没错!但是,在 Page 模型中,没有 has_one :page。你可以看到我对我的主要帖子所做的更改。提前感谢您的帮助!
  • 那么是什么决定了User 的帐户类型是Page 还是User.profile?设置User.account_type的条件是什么?

标签: ruby-on-rails has-one


【解决方案1】:

也许proc 有效?

class User < ActiveRecord::Base
  TYPES = { 'user' => 'Profile', 'page' => 'Page' }
  has_one :profile, :class_name => proc { TYPES[self.type].constantize }
end

如果可行,请考虑添加一个表来存储用户类型:

class User < ActiveRecord::Base
  TYPES = { 'user' => 'Profile', 'page' => 'Page' }
  has_one :profile, :class_name => proc { TYPES[self.type].constantize }
  belongs_to :user_type
end

class UserType < ActiveRecord::Base
  has_many :users
end

【讨论】:

  • 可能条件验证也会这样做。 :) 但是多态在这种情况下确实是不错的选择。
  • 是的,但不应该反过来吗?抱歉,我的英语有时会限制我。主页或个人资料属于用户,而不是相反。
  • 我试过 lambda,并添加到用户模型: has_one :profile, :class_name => ( lambda { return TYPES[self.type] })
  • 这看起来像是在做戏。但我现在的问题是,Rails 如何决定使用什么?
  • 我不知道那个:) 你可以提出一个新的问题。考虑发布您找到的问题的答案以供将来参考。
猜你喜欢
  • 2017-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-12
  • 1970-01-01
  • 2017-04-30
相关资源
最近更新 更多