【发布时间】:2015-09-14 06:43:35
【问题描述】:
我有 2 个模型 Collection 和 Post 并且帖子嵌套在集合中:
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