0

我正在构建一个具有UserProduct类的RoR应用程序。一个用户很多照片都可能是一个产品,但每个用户也必须有一个profile_pictureRails针对可能映射到不同模型类型的模型的活动记录关联

用户:

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 

请使用在轨道上4红宝石和sqlite3的数据库注意IM

回答

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,还可以通过一个型号名称来完成:在corresponging列<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 
+0

谢谢,有没有办法链接配置文件图片,所以我可以访问它@ user.profile_picture呢? – user3576112 2014-08-31 18:43:28

+0

@ user3576112看起来像'has_one:profile_picture,class_name:“Picture”,如::imageable'。相似的东西。 – 2014-08-31 19:45:32

+0

谢谢,这将被保存为用户表中的引用还是只是一个picture_id? – user3576112 2014-08-31 19:53:04