html - Rails 使用复选框为帖子添加标签(多对多)

标签 html ruby-on-rails ruby ruby-on-rails-4

我有一个具有多对多关系的 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它添加了 tagpost .
我在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/

相关文章:

ruby - 如何让 Ruby 的 RestClient 使用多值查询参数?

angularjs - 嵌套的ui.bootstrap.accordion 打开所有嵌套的 Accordion

php - jQuery 不会删除内存游戏对

javascript - 如何使用 jquery 将鼠标悬停在不同的元素上。

javascript - 将所有子 div 彼此靠近

ruby-on-rails - 找不到 Ubuntu RVM Rails bash 命令

javascript - 在javascript中从ruby Controller 调用函数

ruby-on-rails - 如何隐藏json文件的分页

jquery - 在 Bootstrap 模态之间切换

java - C/C++以外语言的逆向调试