2012-09-09 39 views
0

如果我有这样的关系,has_and_belongs_to_many HABTM领域

class Article < ActiveRecord::Base 
    has_and_belongs_to_many :topics 
end 

class Topics < ActiveRecord::Base 
    has_and_belongs_to_many :articles 
end 

我有存储在表中的主题下主题已经预先定义的列表。每个文章必须有3个主题与之相关联。如果我创建一篇新文章,代码怎么会看起来与控制器视图?什么是最有效和正确的方式来创建这个?

回答

2

将三个微调器字段添加到您的表单中,并使用主题标识符作为数据和主题名称作为标签填充它们。幸运的是,有帮助你完成大部分重任的人。 See here有关collection_select的详细信息。下面是该链接取一个例子:

<%= collection_select(:person, :city_id, City.all, :id, :name) %> 

在你的控制器,你可以创建基于选择的IDS必要的关联。它应该是这个样子:

_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