2013-10-07 60 views
1

我試圖實現一個丟失和找到的數據庫。 我有兩個模型,UserItem。用戶可能會丟失某件物品並找到物品。而一件物品可以有一個發現它的用戶和丟失它的用戶。我希望能夠通過不同的名稱引用相同的模型,例如通過不同的名稱關聯相同的模型兩次

user.found_items, user.lost_items, item.founder, item.losser 

現在的我能夠做到:

user.foundsuser.lostsuser.items返回從losts

items
class User < ActiveRecord::Base 
    has_many :founds 
    has_many :items, through: :founds 

    has_many :losts 
    has_many :items, through: :losts 
end 

class Lost < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :item 
end 

class Found < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :item 
end 

class Item < ActiveRecord::Base 
    has_one :found 
    has_one :user, through: :found 

    has_one :lost 
    has_one :user, through: :lost 
end 

回答

0

我會做非常類似的事情只是將其重命名爲清楚起見,並添加一些你想要的功能的方法。

class User < ActiveRecord::Base 

    has_many :found_items 
    has_many :items, through: :found_item 

    has_many :lost_items 
    has_many :items, through: :lost_item 

    def items_found 
    self.found_items.map {|i| i.item.name } 
    end 

    def items_lost 
    self.lost_items.map {|i| i.item.name } 
    end 

end 

class LostItem < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :item 
end 

class FoundItem < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :item 
end 

class Item < ActiveRecord::Base 
    has_one :found_item 
    has_one :user, through: :found_item 

    has_one :lost_item 
    has_one :user, through: :lost_item 

    def finder 
    self.found_item.user.name 
    end 

    def loser 
    self.lost_item.user.name 
    end 
end 
相關問題