เราจะทำการเำพิ่มcommentsให้กับblogของเราโดยที่ความสัมพันธ์ระหว่างcommentกับarticle
เป็น(Article has many Comments and Comment belongs to Article)
1. ruby script/generate scaffold comment title:string description:string article_id:integer
2.rake db:migrate
3.ใน model/comment.rb
belongs_to :article
4.ในmodel/article.rb
has_many :comments
5.ในconfig/routes.rbให้
map.resources :article ,has_many=>comments
6.rake db:migrate
7.ใช้conceptเดิม เหมือนกับ author กับ article โดยในหน้า่ของshow.html.erb
ของcontroller =>articles ให้เขียนform_for เข้าไปยังaction create ของ controller
=>comments ทำได้ดังนี้
<%form_for :comment, @comment,:url=>article_comments_path(@article) do |f|%>
<%=f.text_field :title%>
<%=f.text_field :description%>
<%=f.submit "send"%>
<%end%>
โดยที่createของcontroller =>comments ให้เขียนโค๊ดดังนี้
@comment=Comment.new(params[:comment])
@article=Article.find_by_id(params[:author_id])
@article.comments<<@comment ใน action=>show ของcontroller=>comments
@comment=Comment.find_by_id(params[:id])
@article_link=Article.find_by_id(@comment.article.id)
redirect_to article_path(@article_link)
ไม่มีความคิดเห็น:
แสดงความคิดเห็น