我是rails的新手,我在使用collection_select保存连接表的嵌套属性时遇到问题.我有模型post,tag和post_tagging.post_tagging是一个连接表.
我想为每个帖子设置多个标签,所以我尝试通过collection_select使用多选,但是当我保存时,只将post_id插入到数据库中.下面是我的代码和日志.
Post.rb
class Post < ActiveRecord::Base
has_many :post_taggings, foreign_key: :post_id, dependent: :destroy
has_many :tags, through: :post_taggings, source: :tag
accepts_nested_attributes_for :post_taggings, reject_if: :all_blank, allow_destroy: true
end
Run Code Online (Sandbox Code Playgroud)
Tag.rb
class Tag < ActiveRecord::Base
has_many :post_taggings, foreign_key: :tag_id, dependent: :destroy
has_many :posts, through: :post_taggings, source: :post
end
Run Code Online (Sandbox Code Playgroud)
post_tagging.rb(我在post_tagging模型中关闭了tag_id和post_id的状态验证,因此我可以获得POST的日志.)
class PostTagging < ActiveRecord::Base
belongs_to :post
belongs_to :tag
#validates :post_id, presence: true
#validates :tag_id, presence: true
end
Run Code Online (Sandbox Code Playgroud)
posts_controller.rb(缩写)
class PostsController < ApplicationController
def new
@post = Post.new
@post.post_taggings.build
end
def new_post_params
params.require(:post).permit(:title, post_taggings_attributes: { :tag_id …Run Code Online (Sandbox Code Playgroud) ruby ruby-on-rails nested-attributes ruby-on-rails-4 collection-select