【发布时间】:2023-03-30 04:35:02
【问题描述】:
我的项目中有一个奇怪的要求。实际上,我有两张桌子(用户,画廊)。我想使用 has_one 和 has_many 关联访问画廊表。主要目的是通过has_one关系获取用户的头像,通过has_many关系获取个人上传的图片。
最初我使用多态关联来解决这个问题(仅供参考,请找到下面的代码 sn-p)。但我认为这不是解决这个问题的正确方法。
有人能解释一下如何以有效的方式处理这种情况吗?
class User < ActiveRecord::Base
attr_accessible :name
has_many :galaries, as: :imageable
has_one :galary, as: :imageable
end
class Galary < ActiveRecord::Base
attr_accessible :name
belongs_to :imageable, polymorphic: true
end
【问题讨论】:
标签: ruby-on-rails activerecord ruby-on-rails-3.2 associations polymorphic-associations