【问题标题】:Selecting from array of id's via includes通过包含从 id 数组中选择
【发布时间】:2015-10-29 03:30:18
【问题描述】:

不确定如何解决我在选择个人时遇到的问题 数组中的 id。

我有商店、产品和价格的模型。商店有很多 (has_many) 产品,并且每个商店的产品有一个 (has_one) 价格。 我正在用 CSV 数据播种数据库。我的应用主要仅用作 API。

Prices.csv(其中 id 为 7 和 8 的产品价格相同 4.25 美元的商店 3):

amount,product_id,store_id
"3.49","{6}","3"
"4.25","{7,8}","3"

create_prices.rb:

create_table :prices do |t|
...
     t.integer :product_id, array: true, default: []
... etc
end

当我尝试包含价格时,问题出现在我的查询中 关联,我收到一条错误消息:

ActiveRecord::StatementInvalid
(PG::UndefinedFunction: ERROR:  operator does not exist: integer[] =
integer LINE 1: ...LEFT OUTER JOIN "prices" ON "prices"."product_id" =
"product...

我认为问题与包含的价格没有正确格式化以处理数组有关?

产品控制器:

class API::ProductsController < ApplicationController
@products = Product.where("products.store_id @> '{?}'", params[:id].to_i).includes(:price).where('prices.store_id = ?', params[:id]).references(:prices).limit(params[:max])
end

Product.rb 模型:

class Product < ActiveRecord::Base
    belongs_to :store
  has_one :price

def as_json(options)
    super(:only => [:id, :name, :description, :image, :weight, :store_id],
      :include => {
            :price => {:only => [:amount, :store_id]}
          }
    )
  end
end

【问题讨论】:

  • 仅对从其他来源复制的内容使用引用格式。如果您引用某人,则需要提供适当的属性信息。
  • @theTinMan 哎呀,我现在删除了报价格式
  • 我认为关联不支持使用这样的数组列

标签: ruby-on-rails ruby postgresql


【解决方案1】:

product_id 的价格不要使用数组数据类型,只需使用整数并为每个商店/产品组合单独记录

然后尝试使用 has_one through 获取价格

class Product < ActiveRecord::Base
  belongs_to :store
  has_one :price, through: :store

在您的控制器中尝试预加载而不是包含,这应该生成 2 个查询,一个用于产品,一个用于带有正确 where 子句的价格

@products = Product.where(store_id: params[:id]).preload(:price)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 2015-12-20
    相关资源
    最近更新 更多