1対多の複数モデルの投稿画面が実装できないことで困っています。
categoriesテーブルとpostsテーブルの1対多のリレーションを貼っていて、その投稿画面が実装できません。
(1つのカテゴリーに複数の投稿という関係性です。)
オプションのaccepts_nested_attributes_forを使用し、ストロングパラメータに設定するところまではわかったのですが、
テーブルに全てのカラムが保存できなくなってしまいました。
わかる方、教えていただきたいです。
class PostsController < ApplicationController def rank @rank = Post.find(Favorite.group(:post_id).order('count(post_id) desc').limit(5).pluck(:post_id)) end def index @search = Post.search(params[:q]) @post = @search.result @posts = Post.order(id: :desc).page(params[:page]).per(10) end def show @post = Post.find(params[:id]) @comments = @post.comments @comment = Comment.new end def new @post = Post.new end def create @post = Post.new(post_params) @post.user_id = current_user.id if @post.save redirect_back(fallback_location: @post) else redirect_back(fallback_location: @post) end end def destroy end end private def post_params params.require(:post).permit(:title,:content,posts_attributes: [:id, :category_id]) # ストロングパラメータ end
posts/new.html.erb
<div class="text-center"> <h1>新規投稿画面</h1> </div> <div class-"row"> <div class="col-sm-6 offset-sm-3"> <%= form_with(model: @post, local: true) do |f| %> <div class="form-group"> <%= f.label :title, 'タイトル' %> <%= f.text_field :title, class: 'form-control'%> </div> <div class="form-group"> <%= f.label :content, '内容'%> <%= f.text_area :content, class: 'form-control' %> </div> <div class="field"> <%=f.label :category_id, "カテゴリー" %> <%=f.select :category_id, {自律神経:"自律神経", 不眠:"不眠", 頭痛:"頭痛", 便秘:"便秘", 冷え症:"冷え症"}%> <div class="text-center"> <%= f.submit '投稿'%> </div> </div> </div> <%end%>
class Category < ApplicationRecord has_many :posts accepts_nested_attributes_for :posts end
2.5.3 :002 > Post.new => #<Post id: nil, title: nil, content: nil, user_id: nil, category_id: nil, created_at: nil, updated_at: nil> 2.5.3 :003 >
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/08/30 02:36