2015-10-28 30 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)