###はじめに
掲示板の投稿のようなものをつくってます。
Post(id,user_id,title,text,parent_id)
parent_idが
nil->投稿
nilじゃない->コメント
っていうかんじで考えてます。
class Post < ApplicationRecord has_many :comments, class_name: "Post", foreign_key: "parent_id" belongs_to :post, optional: true, foreign_key: "parent_id" end
投稿の個別ページ(show.html.erb)でコメントできるようにしたいです。
###わからないこと
このやり方で会ってますか?
@post = Post.find(params[:id])
@comment = Post.new
あと、
f.hidden_field(:parent_id, :value => @post.id)は
params[:comment][:parent_id]で取れますか?
posts/show.html.erb
<h4><%= @post.title%></h4> <h4><%= @post.body%></h4> <%= form_for(@comment, url: posts_comments_url) do |f| %> <div class="field"> <%= f.label :body %> <%= f.text_field :body %> <% f.hidden_field(:parent_id, :value => @post.id)%> <%= f.submit "コメント" %> </div> <% end %>
class PostsController < ApplicationController def index @posts = Post.all end def new @post = Post.new end def create @post = Post.new(post_params) if @post.save flash[:info] = "投稿に成功しました" redirect_to posts_url else render 'new' end end def show @post = Post.find(params[:id]) @comment = Post.new end def comment_create @comment = Post.new(comment_params) @comment.attribute = { parent_id: params[:post][:parent_id] } if @comment.save flash[:info] = "コメントの投稿に成功しました" redirect_to post_url(params[:post][:parent_id]) else render 'new' end end private def post_params params.require(:post).permit( :title, :body) end def comment_params params.require(:post).permit(:body, :parent_id) end end
###追記
間違ってました。
×<% f.hidden_field(:parent_id, :value => @post.id)%>
〇<%= f.hidden_field(:parent_id, :value => @post.id)%>
"post"=>{"body"=>"test", "parent_id"=>"1"}, "commit"=>"コメント"}
なのでparams[:post][:parent_id]です。
@post = Post.find(params[:id])
@comment = Post.new
このやり方で大丈夫ですか?ほかの方法があったりしますか?
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。