2015-10-28 35 views
2

不知道如何解决我遇到的问题,从数组中选择一个单独的 ID。从ID的阵列中选择通过包括

我有一个商店,产品和价格模型。商店有许多 (has_many)产品,并且产品每个商店有一个(has_one)价格。 我使用CSV数据为数据库播种。我的应用程序主要用作API。

Prices.csv(其中产品标识: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 
+0

只能使用报价格式为您从其他来源复制的内容价格。如果您要引用某人,则需要提供适当的属性信息。 –

+0

@theTinMan哎呀,我现在删除了报价格式 –

+0

我不认为相信协会支持使用这样的数组列 –

回答

0

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

然后尝试使用has_one直到价格

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

在你的控制器尝试预加载,而不是包括,本应产生2个查询,一个是产品,一个是用正确的where子句

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