在表单中添加三个微调器字段,并使用主题 id 作为数据和主题名称作为标签填充它们。幸运的是,有表单助手可以为您完成大部分繁重的工作。有关的详细信息,请参见此处collection_select
。这是从该链接中获取的示例:
<%= collection_select(:person, :city_id, City.all, :id, :name) %>
在您的控制器中,您可以根据选择的 id 创建必要的关联。它应该看起来像这样:
_form.html.erb
<% form_for @article do |f| %>
...
<%= collection_select(:article, :topic_id_1, Topic.all, :id, :name) %>
<%= collection_select(:article, :topic_id_2, Topic.all, :id, :name) %>
<%= collection_select(:article, :topic_id_3, Topic.all, :id, :name) %>
...
<% end %>
acticle_controller.rb
def create
...
@article.topics << Topic.find params[:topic_id_1]
@article.topics << Topic.find params[:topic_id_2]
@article.topics << Topic.find params[:topic_id_3]
...
end