Ruby on rails Rails在更新方法中更新相关的模型数据
我有这样的代码:Ruby on rails Rails在更新方法中更新相关的模型数据,ruby-on-rails,ruby,Ruby On Rails,Ruby,我有这样的代码: 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+/, "").up
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>
其他产品交叉列表没有破坏 我怎样才能解决这个问题 型号:
class Oil < ActiveRecord::Base
has_many :other_products_cross_lists, :foreign_key => 'main_id'
class OtherProductsCrossList < ActiveRecord::Base
belongs_to :oil
class Oil'main\u id'
类OtherProductsCrossList
其他产品交叉列表与您的机油型号有关。
不能在数组或ActiveRecord:Relation对象上使用update_属性
你应该做的是
@oil.other_products_cross_lists.each {|list| list.update_attributes(:cross_value => @oil.model.to_s.gsub(/\s+/, "").upcase)}
破坏
你可以用
@oil.其他产品交叉列表.全部删除
或
为了清楚起见,您应该检查一下“全部删除”和“全部销毁”之间的区别。因为错误显示“其他产品交叉列表”是一种关系(我假设您的型号
机油
有许多其他产品交叉列表
)
update\u属性
是模型实例的方法,而不是关系的方法
我真的不明白,你想用你的update\u attribute
做什么,但是如果用户嵌套了\u属性,那么
@oil.update_attributes(params[:oil])
负责更新关系
另外,如果您将
Oil
和OtherProducts
之间的关系定义为dependent::destroy
Rails处理依赖记录的删除。oh,好的)也许再写一个查找结果来选择其他相关的\u产品\u交叉\u列表会更容易?在@oil对象上调用其他\u产品\u交叉\u列表非常好。酷!非常感谢你。当我试图更新活动记录关系对象中的列时,这半天我都在苦苦挣扎。你的回答拯救了我的工作:请你发布机油的型号定义。
@oil.other_products_cross_lists.destroy_all
@oil.update_attributes(params[:oil])