もう1つは冗長すぎると思われるので、この質問を書き直しました。私は次のモデル構造を持っており、一連のファイルをアップロードすることに興味があります(ビルダー経由で2回ずつ)。ネストされた属性とフォームハッシュとやりとりし、user_idをcurrent_user.idに設定する
class ItemsController < ApplicationController
...
def update
item=params[:item]
item[:assets_attributes].values do |v|
v[:asset][:user_id]=3 # just hard-code it to see if workig
end
if @item.update_attributes(item)
flash[:notice]="Menu Item has been updated #{undo_link}"
else
flash[:notice]="Menu Item has not been updated"
end
end
で:ここ
<form accept-charset="UTF-8" action="/arc/items/70" class="edit_item" enctype="multipart/form-data" id="edit_item_70" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="_method" type="hidden" value="put" /><input name="authenticity_token" type="hidden" value="NnaCxwmfy2zT8MnN7oNQnOx0xYXkgKUs+NbIh8+8cL4=" /></div>
<div class='files'>
<input id="item_assets_attributes_70_asset" name="item[assets_attributes][70][asset]" type="file" />
<input id="item_assets_attributes_70_description" name="item[assets_attributes][70][description]" size="30" type="text" />
<input id="item_assets_attributes_71_asset" name="item[assets_attributes][71][asset]" type="file" />
<input id="item_assets_attributes_71_description" name="item[assets_attributes][71][description]" size="30" type="text" />
</div>
<input name="commit" type="submit" value="Update Menu item" />
</form>
、それと対話するためのコントローラである:
class Item < ActiveRecord::Base
has_many :assets, :as => :assetable, :dependent => :destroy
accepts_nested_attributes_for :assets, :allow_destroy => true, :reject_if => lambda { |a| a[:asset].blank? }
attr_accessible :assets_attributes, :asset
...
end
class Asset < ActiveRecord::Base
belongs_to :assetable, :polymorphic => true
attr_accessible :name, :user_id, :description ...
...
end
relat多型が、私は、フォーム全体をコピーした場合、私はわかりません私の資産クラス、user_idはNEVERに設定されます。どうすればこの仕事をすることができますか?私は明らかにcurrent_user.idを取得したい。私が気づいた3.1
編集2
一つのことがあれば私はインスタンス変数を設定することであるレールを使用して
THX
編集#1
ループを作成してビューにデバッグすると、このループが実行されていないという意味にはなりませんでした。
item[:assets_attributes].values do |v|
v[:user_id]=3
@a="here is a string"
end
また、項目モデルに対して、項目クラスの適切なattr_accessibleを更新しました。
THXショーンを試してみて、私はattr_accessibleにUSER_IDている(上記更新)とRails 3.1を使用しています - 私は、構文の問題が資産を反復処理してありますかなり確信しています。おそらくasset.userを割り当てることは意味をなさないでしょうし、default_values before_saveに 'self.user_id = self.user.id'を入れていますか? – timpone
asset.userを割り当てることは、そのユーザーのIDにasset.user_idを設定することと同じです。 user_idも明示的に設定する必要はありません.Railsがそれを処理します。 – Shaun