【发布时间】:2014-08-31 20:34:48
【问题描述】:
我有两个类Product 和user,它们与多态类型有has_many 关系。
class User < ActiveRecord::Base
has_many :pictures, as: :imageable
end
class Product < ActiveRecord::Base
has_many :pictures, as: :imageable
end
class Picture < ActiveRecord::Base
belongs_to :imageable, polymorphic: true
end
我还想为profile_picture 的用户模型添加一个新属性,因此@user.profile_picture 将返回一个图片对象。如何做到这一点?特别是向用户添加外键的迁移。
编辑:我已经更新了用户模型
has_one :profile_picture, class_name: "Picture", foreign_key: "profile_picture_id"
并添加了以下迁移
add_column :users, :profile_picture_id, :integer
但是,如果有人能解释我到底做错了什么,我似乎无法设置个人资料图片,我将不胜感激。谢谢!
【问题讨论】:
-
我查看了该链接,我当前的多态关联来自该链接。我不明白的是如何向用户模型添加新的属性,该属性将是图片类型。
-
has_one :picture, as: :profile_picture -
你好。你没有足够接近我的回答:stackoverflow.com/questions/25594975/…
-
抱歉更新问题更清楚
标签: ruby-on-rails ruby ruby-on-rails-4 rails-activerecord