nested object formは以下のrailscast動画を見れば把握できます
チェックボックスを使用するときはちょっとめんどくさかったのでメモ
基本
Article model
class Article < ActiveRecord::Base
attr_accessible :articles_categories_attributes
has_many :categories, :through => :articles_categories
has_many :articles_categories, :dependent => :destroy
accepts_nested_attributes_for :articles_categories, :allow_destroy => true
end
ArticlesCategory model
class ArticlesCategory < ActiveRecord::Base
attr_accessible :article_id, :category_id
belongs_to :article
belongs_to :category
end
Category model
class Category < ActiveRecord::Base
attr_accessible :name
has_many :articles, :through => :articles_categories
has_many :articles_categories, :dependent => :destroy
end
view、update method
view
<% Category.all.each do |category| %>
<% check_flag = @article.articles_categories.any? { |articles_category| articles_category.category_id == category.id } %>
<%= check_box_tag "article[articles_categories_attributes][][category_id]", category.id, check_flag %>
<%= category.name %>
<% end %>
update method
def update
ArticlesCategory.transaction do
@article = Article.find(params[:id], :lock => true)
@article.articles_categories.clear
@article.update_attributes!(params[:interview_article])
end
flash[:notice] = 'Article was successfully updated.'
redirect_to :action => 'index'
rescue ActiveRecord::RecordInvalid
render :action => 'edit'
end