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

相關問題