我有
User
那个has_one :profile
。我有
Profile
一些属性,每个个人资料都有共同点。我想要一些
Users
有一个Sub_profile
或。Coach_profile
Student_profile
Profile
我打算在和 这些之间使用多态关系,Sub_profiles
以允许每个User
都有自己的基本Profile
然后有他们适当的Sub_profile
.
这就是我被打结的地方。
我很难弄清楚belongs_to
, has_one :profile
,as: :sub_profile
polymorphic: true
和dependent: :destroy
方法都属于哪里。
在这一点上,了解如何构建这种类型的解决方案的人将能够写出这些关系 - 但我觉得我需要解释我的(有缺陷的)推理,以便以我的方式构建它,以便有人可以帮助我理解为什么我做错了。
我的问题:
同样重要的是要注意,以防不明显,以下代码结构不会导致代码实际按预期工作(如上所述)。我遇到如下错误:
> Coach_profile.create
RuntimeError: Circular dependency detected while autoloading constant Coach_profile
并尝试类似:
> user.profile.build_coach_profile
结果是undefined method build_coach_profile for profile
我的代码背后的原因:
我现在构建代码的方式,我无法弄清楚如何build_sub_profiles
或build_coach_profile
(例如)因为我设计关系的方式不允许这样做。
- 我想要我
Profiles
的,belongs_to :sub_profile, polymorphic: true, dependent: :destroy
因为我希望sub_profile_id
我的profile
桌子上有一个,所以我可以- 参考
profile.sub_profile
- 有不同类型的
sub_profiles
sub_profiles
当 aprofile
被销毁时, destroy 关联
- 参考
- 我希望我的
sub_profiles
(coach
和student
个人资料)has_one :profile, as: :sub_profile
- 所以我的每个类型都可以通过我的表的和字段
sub_profile
属于一个。profile
sub_profile_id
sub_profile_type
profile
- 所以我的每个类型都可以通过我的表的和字段
用户.rb
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_one :profile
end
配置文件.rb
# id :integer not null, primary key
# user_id :integer
# first_name :string(255) not null
# middle_name :string(255)
# last_name :string(255) not null
# phone_number :integer
# birth_date :date not null
# created_at :datetime
# updated_at :datetime
# sub_profile_id :integer
# sub_profile_type :string(255)
#
class Profile < ActiveRecord::Base
belongs_to :user
belongs_to :sub_profile, polymorphic: true, dependent: :destroy
validates_presence_of :first_name, :last_name, :birth_date
validates_length_of :phone_number, {is: 10 || 0}
end
教练简介.rb
# id :integer not null, primary key
# coaching_since :date
# type_of_coach :string(255)
# bio :text
# created_at :datetime
# updated_at :datetime
#
class CoachProfile < ActiveRecord::Base
has_one :profile, as: :sub_profile
end
student_profile.rb
# id :integer not null, primary key
# playing_since :date
# competition_level :string(255)
# learn_best_by :string(255)
# desirable_coach_traits :text
# goals :text
# bio :text
# created_at :datetime
# updated_at :datetime
#
class StudentProfile < ActiveRecord::Base
has_one :profile, as: :sub_profile
end
我在这里错误地接近了一些东西。如何正确设置几个sub_profiles
和父级之间的多态关系profile
?