gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 09:02:08 25 4
gpt4 key购买 nike

我有一个具有多对多关系的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com