2013-07-30 48 views
0

我有這樣的代碼:在Rails的更新方法更新有關的模型數據

def update 
    @oil = Oil.find(params[:id]) 
    @product_types = ProductType.all  
    if @oil.update_attributes(params[:oil]) 
     if @oil.other_products_cross_lists.update_attributes(:cross_value => @oil.model.to_s.gsub(/\s+/, "").upcase) 
     redirect_to admin_oils_path 
     end 
    else 
     render :layout => 'admin' 
    end 
    end 

但是當我運行它,我得到:

undefined method `update_attributes' for #<ActiveRecord::Relation:0x007f7fb4cdc220> 

,並沒有更新我的other_products_cross_lists ......此外,我嘗試update_attribute並得到相同的錯誤。

我做錯了什麼?

而且當我運行我的破壞方法

def destroy 
    @oil = Oil.find(params[:id]) 
    if @oil.destroy 
     if @oil.other_products_cross_lists.destroy 
     redirect_to admin_oils_path 
     end 
    else 
     render :layout => 'admin' 
    end 
    end 

other_products_cross_lists並沒有摧毀...

我怎樣才能解決這個問題?

型號:

class Oil < ActiveRecord::Base 
    has_many :other_products_cross_lists, :foreign_key => 'main_id' 

class OtherProductsCrossList < ActiveRecord::Base 
    belongs_to :oil 
+0

請問您可以發佈'Oil'的模型定義。 –

+0

@MartinM我加了 –

回答

1

other_products_cross_lists是你的油模型的關聯。 您不能在Array或ActiveRecord:Relation對象上使用update_attributes。

你應該做的是

@oil.other_products_cross_lists.each {|list| list.update_attributes(:cross_value => @oil.model.to_s.gsub(/\s+/, "").upcase)} 

銷燬

可以使用

@oil.other_products_cross_lists.delete_all

@oil.other_products_cross_lists.destroy_all 

你爲了清楚起見,應該檢查delete_all和destroy_all之間的區別。

+0

哦,好的)也許這會更容易寫一個更多的查找選擇other_products_cross_lists相關? –

+0

在您的@oil對象上調用other_products_cross_lists是非常好的。 –

0

的錯誤說other_products_cross_lists是一個關係(我假設你的模型oil的has_many other_products_cross_lists)。

update_attribute是模型實例的方法,而不是關係方法。

我真的不明白,你想和你update_attribute做什麼,但如果用戶nested_attributes,然後

@oil.update_attributes(params[:oil]) 

需要更新的關係的照顧。

此外,如果您將您與OilOtherProducts之間的關係定義爲dependend: :destroy Rails將處理依賴記錄的清除。