接下來我們可以做一個留言功能,
讓其他讀者在瀏覽網站的時候可以給出回饋,
或是可以在文章下面做出一些額外的討論,
rails g model Comment cotent:text user:belongs_to
article:belongs_to deleted_at:datetime:index
#belogs_to建立關聯,deleted_at 的屬性,類型為 datetime,
# 並添加了一個索引index
has_many :comments
<%= form_with(model: @comment) do |f| %>
<%end%>
在 article C 的 show 裡面把 comment new 出來
def show
@comment = Comment.new
end
resources :articles do
resources :comments,only: [:create, :destroy],
shallow: true
end
shallow 會判斷路徑需不需要掛 article
6. 修改 show 的 V 表單路徑
<%= form_with(model: @comment,
url: article_comment_path(@article.id)) do |f| %>
只給@comment會猜錯,給他路徑url
# 也可多給一個@article讓表單去猜
<%= form_with(model: [@article, @comment]) do |f| %>
<%end%>
在 show V 裡面建立 input 表單
<%= form_with(model: [@article, @comment],data: {turbo: false}) do |f| %>
<div>
<%= f.label :content, '留言內容' %><br />
<%= f.text_area :content%>
</div>
<%= f.submit '新增留言'%>
<% end %>
rails g controller comments
before_action :authenticated_user! //登入後才能留言
before_action :find_article, only: [:create] //找出文章的id
def create
# @comment = Comment.new(comment_params)
# @comment.user = current_user 找作者是誰
# @comment.artcile = @artcile 找第幾篇文章
@comment = @artcile.comments.new(comment_params)
if @comment.save
#redirect_to articles_path(@artcile), notice: '留言成功'
else
render "articles/show"
end
end
private
def find_article
@article = Article.find(params[:article_id])
end
清洗
def comment_params
params.require(:comment)
.permit(:content)
.merge(user: current_user)
end
def show
@comment = Comment.new
@comments = @article.comments.order(id: :desc)
end