Rails活动记录关联模型可以映射到不同的模型类型

时间:2014-08-31 18:25:40

标签: ruby-on-rails ruby sqlite ruby-on-rails-4 rails-activerecord

我正在构建一个具有UserProduct类的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.htmlhttp://guides.rubyonrails.org/migrations.html我不明白应该如何形成这些关系,或者数据库中应该存储外键的位置。

我无法查看用户或产品表的架构(rake db:migrate在运行时不会抱怨),因为架构文件中返回了以下错误(我假设这与profile_picture中的# Could not dump table "users" because of following NoMethodError # undefined method `[]' for nil:NilClass 有关。但我不确定如何处理:

{{1}}

请注意我在rails 4和sqlite3数据库上使用ruby

1 个答案:

答案 0 :(得分:1)

Rails文档实际上描述了几乎正是你应该做什么。

A polymorphic association

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进行关联,还可以通过模型名称进行关联:相应的列<model>_id<model>_type。与更简单的关联相反,其中类名称是已知的,并且只需要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