2015-11-20 55 views
2

我想分解我的應用程序的註冊過程到不錯的一口大小的塊。Rails 4 update_attributes,嵌套屬性不保存

因此,我通過Ajax發佈表單,並試圖更新該流程的該步驟中可用的一些模型屬性,基本上意味着它們在每個保存點都不會有效。

因此,我一直在使用update_attribute它工作正常。然而,我的一個屬性是一個has_many協會,我很努力得到這個工作。

我有Channel模型與has_many :channel_tags,還accepts_nested_attributes_for :channel_tags。當我使用更新方法時,保存和更新工作正常,但我無法使用update_attributeupdate_attributes

據我所知,我需要使用update_attributes。我想做類似的事情:

@channel.update_attributes(channel_tags_attributes: params[:channel][:channel_tags_attributes]) 

但是,這並不會創建新的channel_tags。我也曾嘗試用:

@channel.update_attributes(tag_params) 

和:

params.require(:channel).permit(channel_tags_attributes: [ :id, :channel_id, :tag_id, :_destroy ]); 

但同樣,它只是似乎沒有做任何事情。

從控制檯檢查時,似乎發生了所有情況,因爲它正在爲數據庫和類別加載Channel

我做錯了什麼,還是有更好的方法呢?

+0

你試過@ channel.update_attributes(PARAMS [:頻道] [:channel_tags_attributes])? –

+0

我們需要更多信息。你能否展示你的表單和/或表單發佈的參數? –

回答

-1

當你正試圖與軌道4那麼你的代碼應該看起來像嵌套的屬性做到這一點,

在標籤模型

has_many :channel_tags 
accepts_nested_attributes_for :channel_tags, allow_destroy: true 

控制器看起來應該像

def update 
    @tag = Tag.find(params[:id]) 
    puts "==== #{tag_params.inspect} ====" 
    puts "==== #{tag_params[:channel_tags].inspect} ====" 
    if @tag.update!(tag_params) 
    redirect_path 
    end 
end 
private 
def tag_params 
    params.require(:tag).permit(:name ,channel_tags_attributes: [:id, :channel_id, :tag_id, :_destroy]) 
end 

雖然更新屬性請檢查服務器日誌,因爲我檢查了您嘗試爲標籤attribs更新的參數。

.update_attributes只有當你想要特定的屬性。 .update將使用HASH作爲參數,我們將其定義爲強參數。

0

嘗試將名稱更改爲允許PARAMS方法: -

def channel_params 
    params.require(:channel).permit(channel_tags_attributes: [ :id, :channel_id, :tag_id, :_destroy ]); 
end 

和用戶該方法在更新屬性: -

def update 
    @channel = Channel.find(params[:id]) 
    if @channel.update_attributes(channel_params) 
     # add your code here 
    end 
end