記事作成時に一緒にseed.rbであらかじめ作ったカテゴリーを選択するように実装しようとしたのですが、カテゴリーが新たに作成されてしまいます。
rails5を使用しています。
ruby
1# seeds.rb 2Category.create(:name => "国内") 3Category.create(:name => "経済") 4Category.create(:name => "エンタメ") 5Category.create(:name => "スポーツ") 6Category.create(:name => "IT") 7Category.create(:name => "地域")
モデル
ruby
1class Category < ApplicationRecord 2belongs_to :article, optional: true 3end
ruby
1class Article < ApplicationRecord 2 has_one :category, dependent: :destroy 3 accepts_nested_attributes_for :category, allow_destroy: true 4end
コントローラー
ruby
1#articles_controller.rb 2def new 3 @article = Article.new 4 @article.build_category 5 end 6 7 # GET /articles/1/edit 8 def edit 9 end 10 11 # POST /articles 12 # POST /articles.json 13 def create 14 @article = Article.new(article_params) 15 respond_to do |format| 16 if @article.save 17 format.html { redirect_to @article, notice: 'Article was successfully created.' } 18 format.json { render :show, status: :created, location: @article } 19 else 20 format.html { render :new } 21 format.json { render json: @article.errors, status: :unprocessable_entity } 22 end 23 end 24 end
View
#new.html.erb <%= render 'form', article: @article, category: @category %>
#_form.html.erb <div class="field"> <%= f.label :カテゴリー %> <%= f.fields_for :category, @article.category do |category| %> <%= category.collection_select(:id, Category.all, :id, :name, {prompt: "選択してください"}, {class: "form-control"}) %> <% end %> </div>
rute
#routes.rb Rails.application.routes.draw do resources :articles # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html root 'articles#index' end
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。