【问题标题】:Associates the same model twice through different name通过不同的名称将同一模型关联两次
【发布时间】:2013-10-07 07:37:43
【问题描述】:

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

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

现在我可以做到:

user.foundsuser.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

【问题讨论】:

    标签: postgresql associations ruby-on-rails-4


    【解决方案1】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-23
      • 1970-01-01
      • 2013-06-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多