忘れないように私的メモ。
コメントモデルに「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`」
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にもきちんと記述されているか確認しとこう!
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で絞りこむように!
resources :notes do
resources :comments
end
コントローラー
note_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
で表示させる。
<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.○○○
で投稿ユーザーの情報が取得できる。
<% @note.comments.each do |comment| %>
<p><%= "#{comment.user.name}さんが、#{comment.body}と言っています" %></p>
<% end %>
こんな感じ。
結構難しかった。
Modelの関係性の構築は比較的簡単だけど、それを動かすにはどうするかが難しいね。
form_for ([@note, @note.comments.build])の式の意味もよくわかってないし・・・
うーん。難しい@@