2015-09-14 63 views
0

我有2種型號CollectionPost和崗位嵌套在集合:添加CURRENT_USER嵌套模型在創建和更新 - Rails的

accepts_nested_attributes_for :posts, allow_destroy: true, reject_if: proc { |attributes| attributes['title'].blank? } 

我想當前用戶的ID添加到帖子中的控制器,所以我定義的私有方法USER_ID添加到每個崗位在collection_params這樣的:

def add_user_and_in_collection_to_posts(collections_params) 

    posts_params=collection_params[:posts_attributes] 
    posts_params.each { |key,post| 
    unless post[:title].blank? 
     post[:user_id]=current_user.id 
    end   
    } 
    collection_params[:posts_attributes]=posts_params 
    p "^^^^^^^XXX^^^^^^^^^" 
    p posts_params 
    p collection_params 
    p "vvvvvvvXXXvvvvvvvvvv" 


end 

在USER_ID將被添加到posts_params但即使分配posts_paramscollection_params[:posts_attributes]日誌,collection_params不會改變。

我的問題是:

首先,是否添加用戶ID的帖子最好的方法是什麼?

二,爲什麼collection_params不會改變?

+0

你在哪裏定義'collection_params'? – nicohvi

+0

@nicohvi我認爲'collection_params'是由rails定義的,用於更新和在控制器中創建方法。我用腳手架來生成我的控制器等... – Pishist

回答

0

我想通了。 collections_param是鐵軌產生的方法,並允許白名單上的屬性,這樣你就可以回來這樣HashMap中之前將屬性添加到collection_params:

def collection_params 
    permited_params=params.require(:collection).permit(:title,:published,:destination_url,posts_attributes: [:id,:title,:_destroy,]) 
    posts_params=permited_params[:posts_attributes] 
    posts_params.each { |key,post| 
    unless post[:title].blank? 
     post[:user_id]=current_user.id 
    end 
    } 
    permited_params 
end