どなたかご教授ください。
現在、1対1の関係でCategoryとPost,1対多の関係でPostとCommentsでwebアプリケーションを制作しようとしています。
PostするときするときにCategoryを選択する仕様を実装し、
post.title,post.name(投稿者),p_cat(ポストに紐づいたカテゴリー)を送信したいです。
###現在postしたときに表示されるエラーメッセージ
ActiveRecord::RecordNotFound in PostsController#create
Couldn't find Category with 'id'=
###Categoryのカラムにすでにデーターは入れています
以下はコンソール上で、Category.allを実行したときの様子です。
$ Category.all => #<ActiveRecord::Relation [#<Category id: 1, p_cat: "#####", created_at: "2017-01-07 13:00:02", updated_at: "2017-01-07 13:00:02">,
###以下のコードは今回のエラーに関係ありそうなコードです
▼routes.rb(一部)
resources :category do resources :posts end resources :posts do resources :comments end
▼Postの_form.html.erbです
<%= form_for(post) do |f| %> <% if post.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(post.errors.count, "error") %> prohibited this post from being saved:</h2> <ul> <% post.errors.full_messages.each do |message| %> <li><%= message %></li> <% end %> </ul> </div> <% end %> <div class="field"> <%= f.label :title %> <%= f.text_field :title %> </div> <div class="field"> <%= f.label :name %> <%= f.text_field :name %> </div> <%= f.collection_select :id, Category.all, :id, :p_cat %> <div class="actions"> <%= f.submit %> </div> <% end %>
▼categoryのdb>migrateファイルです
class CreateCategories < ActiveRecord::Migration[5.0] def change create_table :categories do |t| t.string :p_cat t.timestamps end end end
▼postのdb>migrateファイルです
class CreatePosts < ActiveRecord::Migration[5.0] def change create_table :posts do |t| t.string :title t.string :name t.references :category, foreign_key: true t.timestamps end end end
▼posts_controller.rbのcreateアクションです
def create @category = Category.find(params[:category_id]) @post = @category.posts.create(post_params)

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。