【问题标题】:Trouble with simple Rails nested associations where clause for parent简单的 Rails 嵌套关联 where 父子句的问题
【发布时间】:2018-09-09 13:54:44
【问题描述】:

我有以下型号:

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

连接看起来正确,但 where 子句似乎失败了。

【问题讨论】:

    标签: ruby-on-rails rails-activerecord


    【解决方案1】:

    ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: missing 表“shopping_trip”的 FROM 子句条目

    您需要在where 中指定表名 而不是关联名。所以shopping_trip 应该是shopping_trips

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

    【讨论】:

      【解决方案2】:

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

      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】:

        检查这个...

        all_purchase = 购买.all

        all_purchase.each 做 |each_purchase| each_purchase.shopping_trip.business 结束

        【讨论】:

        • 这如何回答这个问题?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-01
        • 1970-01-01
        • 2020-12-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多