2015-09-14 62 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