###はじめに
掲示板の投稿のようなものをつくってます。
Post(id,user_id,title,text,parent_id)
parent_idが
nil->投稿
nilじゃない->コメント
っていうかんじで考えてます。
###わからないこと
いい感じに関連付けて
post.commentsとか
comment.post,
post.comments.createとか
使えるようにできませんか?
post.comments.create
class post has_many :comment, class_name: "Post"
みたいな感じで。
あと投稿とコメントはテーブルを分けたほうがいいですか?
###追記
class Post < ApplicationRecord has_many :comments, class_name: "Post", foreign_key: parent_id belongs_to :post, optional: true, foreign_key: parent_id end
sqlite> .schema posts CREATE TABLE "posts" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "title" varchar, "body" text, "parent_id" integer, "user_id" integer, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL, CONSTRAINT "fk_rails_5b5ddfd518" FOREIGN KEY ("user_id") REFERENCES "users" ("id") ); CREATE INDEX "index_posts_on_parent_id" ON "posts" ("parent_id"); CREATE INDEX "index_posts_on_user_id" ON "posts" ("user_id");
class CreatePosts < ActiveRecord::Migration[5.1] def change create_table :posts do |t| t.string :title t.text :body t.integer :parent_id t.references :user, foreign_key: true t.timestamps end add_index :posts, :parent_id end end
class PostsController < ApplicationController def index end def new @post = Post.new end def create end def show end end
Rails.application.routes.draw do devise_for :users, controllers: { ・ ・ ・ resources :posts end
<%= form_for(@post) do |f| %> <div class="field"> <%= f.label :title %> <%= f.text_field :title %> <%= f.label :body %> <%= f.text_field :body %> <%= f.submit "投稿" %> </div> <% end %>
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/08/15 05:00
2019/08/15 05:20
2019/08/15 05:24
2019/08/15 05:29 編集
2019/08/15 05:35
2019/08/15 05:41
2019/08/15 06:03 編集
2019/08/15 06:06
2019/08/15 06:20