2012-02-23 34 views
1

這是此問題的後續where's the appropriate place to handle writing the current_user.id to an object我有以下模型。具有資產的項目。我在該項目中是using accepts_nested_attributes_for :assets如何爲accept_nested_attributes_for模型分配值

我想將current_user.id值分配給每個資產。通常我只是做@item.update_attributes(params[:item])來保存它。在這種情況下,是否有簡單的一行方式來設置每個資產的user_id?

展望開發日誌中,我看到此處的值:

item[assets_attributes][10][asset] 

我應該通過所有這些迭代,並設置爲user_id值?

THX

這裏的一些更多的HTML(項目 - > MENU_ITEM;上面已經離開了簡化)。下面提出的控制器sol'n似乎不起作用。我在控制器的層面上做得很好。任何幫助讚賞。

<div class='image-row'> 
    <input id="menu_item_assets_attributes_18_asset" name="menu_item[assets_attributes][18][asset]" type="file" /> 
    <input id="menu_item_assets_attributes_18_description" name="menu_item[assets_attributes][18][description]" size="30" type="text" /> 
    </div> 
    <div class='image-row'> 
    <input id="menu_item_assets_attributes_19_asset" name="menu_item[assets_attributes][19][asset]" type="file" /> 
    <input id="menu_item_assets_attributes_19_description" name="menu_item[assets_attributes][19][description]" size="30" type="text" /> 
    </div> 
<div class='image-row'> 
    <a href="/images/371/5ea19b9cfa534f1c1f5457ebb149d4259a662f88_huntbch_original.jpg?1329917713"><img alt="D5cc413a1748fb43b0baa2e32e29b10ac2efda10_huntbch_thumb" src="/images/371/d5cc413a1748fb43b0baa2e32e29b10ac2efda10_huntbch_thumb.jpg?1329917713" /></a> 
<div class='img-row-description'> 
    <label for="menu_item_assets_attributes_20_description">Description</label> 
    <input id="menu_item_assets_attributes_20_description" name="menu_item[assets_attributes][20][description]" size="60" type="text" value="here is my comment" /> 
    <label for="menu_item_assets_attributes_20_destroy">Destroy</label> 
    <input name="menu_item[assets_attributes][20][_destroy]" type="hidden" value="0" /><input id="menu_item_assets_attributes_20__destroy" name="menu_item[assets_attributes][20][_destroy]" type="checkbox" value="1" /> 
    </div> 

回答

0

如何遍歷參數數組並設置像這樣的值:

params[:item][:assets_attributes].map! do |asset_params| 
    asset_params[:user_id] = current_user.id 
end 

現在你可以像以前一樣使用update_attributes(params[:item])

+0

在這種情況下處理id值的語法是否?我得到一個錯誤'不能將符號轉換爲整數'; thx求助!試圖快速拿起導軌 – timpone 2012-02-23 18:32:28

1

這個答案可能比你以前的答案有點混淆。

如果每個資產都必須有一個項目,那麼從資產中完全刪除擁有用戶的想法可能會更明智:您可以通過查詢附加項目(如@asset.item.user)來找到擁有用戶。但是,如果用戶可以獨立於項目擁有資產,我認爲這不適用於您。

如果資產始終以項目的嵌套方式創建,則資產的before_create可以分配所需的值。像這樣的事情在asset.rb:

before_create :assign_user 

def assign_user 
    self.user = self.item.user if self.item && self.item.user 
end 

最後,如果你只是想這樣做控制器,沃爾夫岡的答案是非常好,將USER_ID添加到每個asset_attributes。

+0

我們的模式需要多個關聯(即可以擁有一個項目,也可以分別擁有一個資產,並且在不同的環境中以促進團隊所有權等事情)。既然如此,我們希望將資產所有權與項目分開存在。 – timpone 2012-02-23 19:02:04

相關問題