【发布时间】:2016-01-08 23:34:41
【问题描述】:
我有一个包含多对多关系的 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 控制台中,如果我使用 post= Post.first tag= Tag.first post.tags<<tag 它会将 tag 添加到 post。
我在post controller 中没有任何特殊代码来处理这个问题。请帮帮我。
【问题讨论】:
-
您的帖子参数进入服务器时是什么样的?另外,你在用
@topic做什么? -
我删除了@topic。请看一下。
标签: html ruby-on-rails ruby ruby-on-rails-4