收集
Rails有一塊特殊的功能,它允許您使用collection_ids
填充associative collections
。我無法找到任何這documenation,但它的存在,因爲我們之前已經使用過它:
#app/controllers/posts_controller.rb
class PostsController < ApplicationController
def create
@post = Post.new post_params
@post.save
end
private
def post_params
params.require(:post).permit(:tag_ids)
end
end
這意味着如果你傳遞任何值到tag_ids
屬性,Rails會保存集合爲您服務。你並不需要做accepts_nested_attributes_for
或任何東西 - 它只是工作
通過使用@Baloo
的select
元素這個後端應允許您填充post_tags
-
個人
如果您想單獨添加這些項目,您需要在控制器中使用<<
or .delete
方法:
#app/controllers/posts_controller.rb
Class PostsController < ApplicationController
def change_tag
@post = Post.find params[:id]
@tag = Tag.find params[:tag_id]
@post.tags << @tag if request.post?
@post.tags.delete(@tag) if request.delete?
end
end
[Documentation](http://guides.rubyonrails.org/association_basics.html#methods-added-by-has-many-collection-singular-ids)is in導軌指南 –