【问题标题】:Add current_user to nested model in Create and Update - Rails在创建和更新中将 current_user 添加到嵌套模型 - Rails
【发布时间】:2015-09-14 06:43:35
【问题描述】:

我有 2 个模型 CollectionPost 并且帖子嵌套在集合中:

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_params 分配给 collection_params[:posts_attributes]collection_params 也不会改变。

我的问题是:

首先,这是将用户 ID 添加到帖子的最佳方式吗?

第二,为什么collection_params不会改变?

【问题讨论】:

  • 你在哪里定义collection_params
  • @nicohvi 我认为collection_params 是由rails 定义的,用于控制器中的更新和创建方法。我使用脚手架来生成我的控制器等...

标签: ruby ruby-on-rails-4 nested-attributes params


【解决方案1】:

我想通了。 collections_param 是由 rails 生成的一个方法,它允许列入白名单的属性,因此您可以在返回 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

【讨论】:

    猜你喜欢
    • 2014-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-30
    • 1970-01-01
    相关资源
    最近更新 更多