LoginSignup
4
2

More than 5 years have passed since last update.

railsでユーザー付きノートモデルにユーザー付きコメント機能を乗せる。

Posted at

忘れないように私的メモ。

コメントモデルに「user_idとnote_id」を取得させるのにはまった@@

前提条件として、Deviseなどでユーザーセッションを持つサイトを作成。

scaffoldでUserモデルを作成してある。

コメントの投稿も、表示も、`views/notes/show.html.erb'から投稿できるように。

モデル設計

それぞれのモデルに関連付けるように設計する。

今回の場合
Userは「ノートを複数所持has_many :notes。また、コメントも沢山している。has_many :comments
Noteは、「色々なユーザーに所持されているhas_many :users、また、色んな人からコメントも貰っているhas_many :comments
Commentは、「ユーザーによって記述されbelongs_to :user、コメントはユーザーに属しているbelongs_to :user`」

terminal
rails g scaffold user name:string
rails g scaffold note title:string
rake db:migrate

rails g scaffold comment user:references note:references
rake db:migrate

で、UserとNoteにhas_manyとかbelongs_toを追記。
Commentにもきちんと記述されているか確認しとこう!

models
class User < ActiveRecord::Base
    has_many :notes
    has_many :comments
end

class Note < ActiveRecord::Base
    belongs_to :user
    has_many :comments, dependent: :destroy 
end

class Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :note
end

ルーティング

ノートからコメントにルーティングできるようにネストにする

commentsをscaffoldで作ってる場合は、不要なルートはonlyで絞りこむように!

route
resources :notes do
    resources :comments
end

コントローラー

note_controllerに関しては、何も記述する必要はない。
コメントへの書き込み作業はcomments_controllerにお任せ

comments_controller
def create
    @note= Note.find(params[:note_id]) #ページ番号を取得します
    @comment = @note.comments.build(comment_params) #commentテーブルに書き込む
    @comment.user_id = current_user.id #セッション中のユーザーidを練りこむ
    respond_to do |format|
      if @comment.save
        format.html { redirect_to (:back), notice: 'Comment was successfully created.' }
    .この変は環境好みに合わせて書き直してくれ。ちなみに、redirect_to (:back)としとくと、前の画面に戻れるで
    .

ビュー。

投稿用部分

投稿したコメントはnotes/show.html.erbで表示させる。

notes/show
<h2>Add a comment:</h2> 
<%= form_for([@note, @note.comments.build]) do |f| %> 
<div class="field"> 
<%= f.label :body %><br /> 
<%= f.text_area :body %> 
</div> 
<div class="actions"> 
<%= f.submit %> 
</div> 
<% end %> 

コメント表示部分

comment.user.○○○で投稿ユーザーの情報が取得できる。

notes/show

<% @note.comments.each do |comment| %>
         <p><%= "#{comment.user.name}さんが、#{comment.body}と言っています" %></p>
        <% end %>

こんな感じ。
結構難しかった。
Modelの関係性の構築は比較的簡単だけど、それを動かすにはどうするかが難しいね。

form_for ([@note, @note.comments.build])の式の意味もよくわかってないし・・・
うーん。難しい@@

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2