2013-07-30 50 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将处理依赖记录的清除。