代码之家  ›  专栏  ›  技术社区  ›  Augusto Samamé Barrientos

父级的简单Rails嵌套关联where子句有问题

  •  0
  • Augusto Samamé Barrientos  · 技术社区  · 6 年前

    class Business < ApplicationRecord
      has_many :shopping_trips
    end
    
    class ShoppingTrip < ApplicationRecord
      belongs_to :business
      has_many :purchases
    end
    
    class Purchase < ApplicationRecord
      belongs_to :shopping_trip
    end
    

    所以一个企业可以有很多次购物旅行,而且每一次购物旅行都可以有很多次购物。

    我试图在Purchase表上运行一个简单的查询,以查找属于特定业务的采购。所以我写这个:

    purchases = Purchase.joins(:shopping_trip => :business ).where(:shopping_trip => {:business_id => 1})
    

    不幸的是它不起作用。我得到以下错误:

    ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "shopping_trip"
    LINE 1: ...sses"."id" = "shopping_trips"."business_id" WHERE "shopping_...
                                                                 ^
    : SELECT "purchases".* FROM "purchases" INNER JOIN "shopping_trips" ON "shopping_trips"."id" = "purchases"."shopping_trip_id" INNER JOIN "businesses" ON "businesses"."id" = "shopping_trips"."business_id" WHERE "shopping_trip"."business_id" = $1
    

    join看起来是正确的,但where子句似乎失败了。

    3 回复  |  直到 6 年前
        1
  •  1
  •   Pavan Cesar    6 年前

    ActiveRecord::StatementInvalid:PG::UndefinedTable:错误:缺少

    表名 where . 所以呢 shopping_trip 应该是 shopping_trips

    purchases = Purchase.joins(:shopping_trip => :business ).where(:shopping_trips => {:business_id => 1})
    
        2
  •  1
  •   max    6 年前

    更好的解决方案是设置间接关联,这样您就可以通过联接模型进行查询,而无需手动联接:

    class Business < ApplicationRecord
      has_many :shopping_trips
      has_many :purchases, through: :shopping_trips
    end
    
    class ShoppingTrip < ApplicationRecord
      belongs_to :business
      has_many :purchases
    end
    
    class Purchase < ApplicationRecord
      belongs_to :shopping_trip
      has_one :business, through: :shopping_trip
    end
    

    您现在可以从任意一侧进行查询:

    @business = Business.eager_load(:purchases).find(1)
    @purchases = @business.purchases
    
    # or
    @purchases = Purchase.eager_load(:buisness).where(businesses: { id: 1 })
    
        3
  •  -1
  •   Arun P    6 年前

    检查这个。。。

    所有购买=购买.all

    结束