2011-06-28 37 views
1

我有用戶其中有產品通過habtm鏈接,這是工作。兩個has_many之間的相同型號的鏈接

我想補充的用戶模型和產品模型之間的聯繫,跟蹤該產品的創造者(誰並不總是自己的產品,當然)

但是,當我在用戶產品寫模型創建一個新的鏈接,應用螺絲,因爲我無法從(很多)業主區分產品創造者產品

你能幫我嗎?這裏是我的模型:

class Product < ActiveRecord::Base 
    belongs_to :group 
    has_and_belongs_to_many :authors 
    has_and_belongs_to_many :users # THIS IS OK (with appart table) 
    has_many :users, :as => creator # THIS LINE DOES NOT WORK AT THE MOMENT 
end 

class User < ActiveRecord::Base 
    has_and_belongs_to_many :products 
    belongs_to :user     # THIS LINE DOES NOT WORK AT THE MOMENT 
    default_scope :order => "username ASC" 
end 

數據庫是好的,我可以存儲從我的產品的創造者列下的USER_ID,但鏈接product.creator.name不工作(因爲模型是不正確的,我認爲),我只能讀取列中的user_id,但不能獲取具有其所有屬性的用戶對象。

REM:user.products完美的作品,但只有當我刪除了創作者我的新鏈接...

謝謝!

回答

0

:as語法用於多態關聯 - 這不是你想要的。您對列名的評論有點含糊,所以我會假設您的products表中有user_id列,該列是該產品創建者的標識(我只包含相關關聯)。

class Product < ActiveRecord::Base 
    has_and_belongs_to_many :users 
    belongs_to :creator, :foreign_key => :user_id, :class_name => "User" 
end 

class User < ActiveRecord::Base 
    has_and_belongs_to_many :products 
    has_many :owned_products, :class_name => "Product" 
end 
+0

我檢查得很快,因爲它還沒有工作。我再也無法訪問我的密鑰創建者,並且product.creator一直返回零(即使我使用SQlite查看器在表格列中看到user_id) –

+0

和user.owned_products不會返回此類列:products.user_id –

+0

正如我所說的,我認爲指向產品創建者的'products'中的列被稱爲'user_id'。將'user_id'更改爲該列被調用的內容。 – smathy

0

有應該是一個不錯的寶石:https://github.com/spovich/userstamp

我用它在我的項目和它的作品很好 - 你只是增加了「可衝壓」到您的模型,然後creator_id(和updater_id)的authomaticly填補。

相關問題