LoginSignup
15
13

More than 5 years have passed since last update.

nested object formsのcheckbox使用例

Last updated at Posted at 2012-10-27

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
15
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
13