gpt4 book ai didi

postgresql - 通过不同的名称关联同一个模型两次

转载 作者:行者123 更新时间:2023-11-29 14:00:48 25 4
gpt4 key购买 nike

我正在尝试实现失物招领处数据库。我有两个型号,UserItem .用户可以丢失一个项目并找到一个项目。一个项目可以有找到它的用户和丢失它的用户。我希望能够通过不同的名称引用相同的模型,例如

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

现在我能做到:

user.founds , user.lostsuser.items将返回 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

最佳答案

我会做一些非常相似的事情,只是为了清楚起见重命名它们并为您想要的功能添加一些方法。

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

关于postgresql - 通过不同的名称关联同一个模型两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19219316/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com