如果您想让用户一次创建多个标签,您只需在帖子的表单中添加一个选择/复选框即可。
<%= form_for(@post) do |f| %>
# ...
<div class="field">
<%= f.label :product_ids %>
<%= f.collection_select :product_ids, Product.all, :name, :id %>
</div>
<% end %>
def post_params
params.require(:post)
.permit(:foo, :bar, product_ids: [])
end
Rails 会自动在连接表中创建记录。
如果您希望用户一一创建链接,您需要设置一个nested route:
Rails.application.routes.draw do
# ...
resources :posts do
resources :taggings, only: :create
end
end
然后您需要在posts/show.html.erb 页面上为每个产品设置一个表单:
<ul>
<% @post.products.each do |product| %>
<li>
<%= product.name %>
<%= form_for [@post, product.taggings.new] do |f| %>
<%= f.hidden_field :product_id %>
<%= f.submit 'tag' %>
<% end %>
</li>
<% end %>
</ul>
您可以稍后使用 CSS/JS 来美化它。
还有一个控制器来处理创建标记。
class TaggingsController < ApplicationController
# POST /posts/:post_id/taggings
def create
@post = Post.find(params[:post_id])
@tagging = @post.taggings.new(product: Product.find(params[:tagging][:product_id]))
if @tagging.save
redirect_to @product, success: 'Tagging saved.'
else
redirect_to @product, error: 'Tagging not saved.'
end
end
end