Rails用于可以映射到不同模型类型的模型的活动记录关联
我正在构建一个具有User
和Product
类的RoR应用程序。 一个用户可能有很多照片,也可能是产品,但每个用户也必须有一个profile_picture
。
用户:
class User < ActiveRecord::Base has_many :pictures end
产品介绍:
class Product < ActiveRecord::Base has_many :pictures end
我正在努力定义目前的pictures
模型:
class Picture < ActiveRecord::Base has_one :user has_one :product end
图片的架构如下(为简洁起见,省略了时间戳):
create_table "pictures", force: true do |t| t.string "image_url" end
最后,我进行了迁移,为用户和产品添加了个人资料图片的链接
class AddPicturesToUsersAndWalks < ActiveRecord::Migration def change add_column :users, :profile_picture, :picture add_column :products, :profile_picture, :picture end end
我已经阅读了http://guides.rubyonrails.org/association_basics.html和http://guides.rubyonrails.org/migrations.html我不明白应该如何形成这些关系或者数据库中的外国人密钥应该存储。
我无法查看用户或产品表的架构( rake db:migrate
在运行时不会抱怨),因为在架构文件中返回以下错误(我假设这与两者中的profile_picture
有关但我不确定如何处理:
# Could not dump table "users" because of following NoMethodError # undefined method `[]' for nil:NilClass
请注意我在rails 4和sqlite3数据库上使用ruby
Rails文档实际上几乎准确地描述了您应该做什么。
多态关联 。
class Picture < ActiveRecord::Base belongs_to :imageable, polymorphic: true # `imageable` is just a name for you to reference and can by anything # It is not a class, a table or anything else # It affects only corresponding DB column names end class User < ActiveRecord::Base has_many :pictures, as: :imageable # read as: I am an `imageable`, I can have a picture as one end class Product < ActiveRecord::Base has_many :pictures, as: :imageable end
在数据库中,这通过不仅通过id
关联,而且通过模型名称关联来实现:在相应的列
和
。 与更简单的关联相反,其中类名称是已知的并且仅需要id
。
class CreatePictures < ActiveRecord::Migration def change create_table :pictures do |t| t.string :data t.integer :imageable_id t.string :imageable_type t.timestamps end end end