2014-01-16 47 views
0

我有以下作用在我的控制器未定義的方法`的update_attributes'爲#<陣列:0xb5d61608>導軌4

cust = Customer.where(email: '[email protected]').pluck(:post_id) 
@posts = Post.find(cust) 
if params[:status] 
    if @posts.update_attribute(:customer_id, customer_id) 
    respond_to do |format| 
     format.json { render json: 'test'} 
    end 
    end 
end 

上面update_attribute拋出未定義的方法錯誤。

卡斯特將返回的ID陣列如[1,2,3]

我怎樣才能做到這一點

回答

4

嘗試:

@posts = Post.where(id: cust) 
@posts.update_all(customer_id: customer_id) 

它構建一個SQL UPDATE語句,並直接將其發送到數據庫。

0

試圖改變查詢以下列方式

卡斯特= Customer.where(電子郵件: '[email protected]')。first.pluck(:POST_ID)

這將返回一個客戶,然後用post @posts = Post.where(id:cust)做同樣的事情。首先

但是,如果你想在@posts中有多個記錄,那麼你需要遍歷它們並單獨更新。

@ posts.each do | post | 如果post.update_attribute(:CUSTOMER_ID,CUSTOMER_ID) 端 端

+0

爲什麼我需要先添加?我使用pluck來生成不僅僅是第一個id值的數組 – overflow

0

嘗試此

CUST = Customer.where(電子郵件: '[email protected]')。摘去(:POST_ID)

Post.update_all({:CUSTOMER_ID,CUSTOMER_ID},{ID:卡斯特})

我們可以包括在where子句update_all查詢本身

相關問題