###Article Model
lang
1class Article < ActiveRecord::Base 2 has_many :articles_categories 3 has_many :categories, through: :articles_categories 4end
###Category Model
lang
1class Category < ActiveRecord::Base 2 has_many :articles_categories 3 has_many :articles, through: :articles_categories 4end
###ArticlesCategory Model
lang
1class ArticlesCategory < ActiveRecord::Base 2 belongs_to :article 3 belongs_to :category 4end
###ArticlesContoller
lang
1class ArticlesController < ApplicationController 2 before_action :set_article, only: [:show, :edit, :update, :destroy] 3 4 def edit 5 #@genreにcategoryの一つであるgenre(国際、環境、貧困、障害など)をいれる 6 @genre = Group.genre.first.categories 7 @selected_categories = ArticlesCategory.where(article_id: params[:id]) 8 @selected_categories_id = [] 9 @selected_categories.each do |sci| 10 @selected_categories_id << sci.category_id 11 end 12 end 13 14 def update 15 begin 16 @article.update!(article_params) 17 redirect_to edit_article_path(@article.id), notice: 'Article was successfully created.' 18 rescue Exception => e 19 render :edit 20 end 21 end 22 23 private 24 def set_article 25 @article = Article.find(params[:id]) 26 end 27 28 def article_params 29 params.require(:article).permit(:title, :kind, :price_category, :place_category, :place, :price, :term_category, :activity_frequent_category, :necessary_time_category, :target, :deadline, :detail_info, :subtitle, :participation_comment, :atmosphere, :participation_number, :men_rate, :women_rate, :user_id, pictures_attributes: [:file, :description], remarkable_points_attributes: [:text], activity_dates_attributes: [:start_date, :end_date], additional_questions_attributes: [:name, :necessary]) 30 end 31end 32
###articles/edit.html.erb
lang
1<%= form_for(@article) do |f| %> 2 <div class="field"> 3 <%= f.label :title %><br> 4 <%= f.text_field :title %> 5 </div> 6 7 <div class="field"> 8 <%= f.label :genre %><br> 9 <% @genre.each do |genre| %> 10 <% if @selected_categories_id.include?(genre.id) then %> 11 <%= check_box "categories", "#{gemre.status}", {:checked => true} %> 12 <% else %> 13 <%= check_box "categories", "#{genre.status}" %> 14 <% end %> 15 <%= label_tag "#{genre.name}" %> 16 <% end %> 17 </div> 18 19 <%= f.submit %> 20 21<% end %> 22
当然ではあるのですが、
このままではarticle_paramsの内容しかupdateされず、
いろいろ試しましたがCategoryの中身をupdateする方法が見つかっていません。
createでは、
lang
1 def create 2 @article = Article.new(article_params) 3 @article.user_id = current_user.id 4 params[:categories].each do |key, value| 5 @article.categories << Category.find(key.to_i) if value == "1" 6 end 7 begin 8 @article.save! 9 redirect_to edit_article_path(@article.id), notice: 'Article was successfully created.' 10 rescue Exception => e 11 render :new 12 end 13 end
こんな感じで保存してます。
ご教授よろしくお願いします。
あなたの回答
tips
プレビュー