這是做blog時如何在文章顯示頁面下方加上訪客留言的筆記,基本上從rails guide來得 6.2 Associating Models 先建立好一對多的關聯 留言model

class Comment < ApplicationRecord
  belongs_to :article
end

文章model

class Article < ApplicationRecord
  has_many :comments
  validates :title, presence: true,
                    length: { minimum: 5 }
end

之後再需要顯示留言的網頁新增form

<%= form_for([@article, @article.comments.build]) do |f| %>
  <p>
    <%= f.label :commenter %><br>
    <%= f.text_field :commenter %>
  </p>
  <p>
    <%= f.label :body %><br>
    <%= f.text_area :body %>
  </p>
  <p>
    <%= f.submit %>
  </p>
<% end %>

這樣子就會自動連到comment的create controller,也因此可以從params得到post_od

 POST   /posts/:post_id/comments(.:format)          comments#create

留言controller

class CommentsController < ApplicationController
  def create
    @article = Article.find(params[:article_id])
    @comment = @article.comments.create(comment_params)
    redirect_to article_path(@article)
  end

  private
    def comment_params
      params.require(:comment).permit(:commenter, :body)
    end
end

或者也可以用下面這種方法, 在form_for指定送出後的url或是action

<%= form_for @comment, url: post_comments_path(@post) do |f| %>

然後在post的show action增加

  def show
    @comment = Comment.new
  end

其他部分都和上面的方法一樣


刪除

因為是nested routes所以刪除的網址長得像這樣 /posts/:post_id/comments/:id(.:format) 所以要把需要的post_id和comment id 傳過去

<%= link_to '刪除留言', post_comment_path(comment.post, comment), method: :delete, data: {confirm: "確定要刪除?"} %>

Written with StackEdit.

results matching ""

    No results matching ""