1

私はそのようなコードを持っています:

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を試しても同じエラーが発生します。

私は何を間違っていますか?

また、destroy メソッドを実行すると

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
4

2 に答える 2

2

other_products_cross_lists は Oil モデルの関連付けです。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 の違いを確認してください。

于 2013-07-30T09:07:22.893 に答える
0

エラーが言うようother_products_cross_listsに、関係です(モデルはoilhas_manyと仮定しますother_products_cross_lists)。

update_attributeリレーションのメソッドではなく、モデルのインスタンスのメソッドです。

あなたが何をしたいのかよくわかりませんupdate_attributeが、ユーザーがnested_attributesの場合、

@oil.update_attributes(params[:oil])

リレーションの更新を処理します。

Oilまた、RailsとOtherProductsasの間の関係を定義するとdependend: :destroy、依存レコードの削除が処理されます。

于 2013-07-30T09:09:06.157 に答える