我有一个具有多对多关系的 Post 模型和 Tag 模型。
发布模型:
class Post < ActiveRecord::Base
has_and_belongs_to_many :tags
end
标签模型:
class Tag < ActiveRecord::Base
has_and_belongs_to_many :posts
end
我还有一个 posts_tags
的连接表:
class JoinPostsAndTags < ActiveRecord::Migration
def change
create_table :posts_tags do |t|
t.integer :tag_id
t.integer :post_id
t.timestamps null: false
end
end
end
现在,我需要提供多项选择来为帖子选择标签。
下面是帖子form.html.erb
<%= form_for @post do |f| %>
<% if @post.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% @post.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :Name %><br>
<%= f.text_field :Name %>
</div>
<div class="field">
<%= f.label :Email %><br>
<%= f.text_field :Email %>
</div>
<div class="field">
<%= f.label :Message %><br>
<%= f.text_area :Message %>
</div>
<% @tags= Tag.all %>
<% if @tags %>
<% @tags.each do |tag| %>
<div>
<%= check_box_tag "post[tag_ids][]", tag.id, @post.tags.include?(tag) %>
<%= tag.name %>
</div>
<% end %>
<% end %>
<br><br>
<%= link_to 'Create Tag', tags_path %>
<br><br>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
它没有将选定的标签添加到帖子中。我需要将选定的标签添加到帖子中。我该怎么做。
但是,在 rails console 中,如果我使用 post= Post.first
tag= Tag.first
post.tags<<tag
它添加了 tag
到 post
.
我在post controller
中没有任何特殊代码来处理这个。请帮助我。
最佳答案
将 {tag_ids:[]}
添加到您的 params
permit
您的 PostsController
参数中,如下所示:
def post_params
params.require(:post).permit(:name, :email, :message, {tag_ids:[]})
end
关于html - Rails 使用复选框为帖子添加标签(多对多),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33065034/