的數據庫設計的動作假設你有所謂的「主題」作爲父母的模型,「評價」作爲一個孩子。 在網址'topics/show/35'上,您可以看到屬於該主題ID#35的所有評論。如何設置與考慮Rails3中
當登錄用戶想在此頁發佈他的新評論時,我應該在topics_controller.rb中寫'comment_create'動作嗎? 或只是在comments_controller.rb中寫'創建'動作,並從這個頁面調用它? 哪一個是常規方式?
如果我所說的「創造」在comments_controller動作,我怎麼能在視圖寫傳遞
- 「型號名稱」添加註釋到
- 「模式ID#」
- 「註釋體'
或者我應該只是單獨寫入的動作也是這樣嗎?
控制器/ comments_controller.rb
def create_in_topic
code here! to add new comment record that belongs to topic....
end
def create_in_user
code here! to add new comment record that belongs to user....
end
爲您的信息,評論添加動作應該是這樣的。
def create
@topic = Topic.find(params[:topics][:id])
@user_who_commented = current_user
@comment = Comment.build_from(@topic, @user_who_commented.id, params[:topics][:body])
@comment.save
redirect_to :back
flash[:notice] = "comment added!"
end
例更新!!!
的意見/主題/ show.html.erb
<table>
<tr>
<th>ID</th>
<th>Title</th>
<th>Body</th>
<th>Subject</th>
<th>Posted by</th>
<th>Delete</th>
</tr>
<% @topic.comment_threads.each do |comment| %>
<tr>
<td><%= comment.id %></td>
<td><%= comment.title %></td>
<td><%= comment.body %></td>
<td><%= comment.subject %></td>
<td><%= comment.user.user_profile.nickname if comment.user.user_profile %></td>
<td> **Comment destroy method needed here!!!** </td>
</tr>
<% end %>
</table>
<%=form_for :topics, url: url_for(:controller => :topics, :action => :add_comment) do |f| %>
<div class="field">
<%= f.label :'comment' %><br />
<%= f.text_field :body %>
</div>
<%= f.hidden_field :id, :value => @topic.id %>
<div class="actions">
<%= f.submit %>
<% end %>
控制器/ topics_controller.rb
def add_comment
@topic = Topic.find(params[:topics][:id])
@user_who_commented = current_user
@comment = Comment.build_from(@topic, @user_who_commented.id, params[:topics][:body])
@comment.save
redirect_to :back
flash[:notice] = "comment added!"
end
謝謝!如果您從頁面/ topics/show/35中逐個刪除已發佈的評論,該怎麼辦?我的意思就像這裏在這個stackoverflow的評論。你在topic_controller.rb中放置'comment_destroy方法'嗎?或者你需要調用'destroy method'並將參數傳遞給comments_controller?哪種方式很平常? – MKK 2012-07-11 00:22:46
不用擔心,它只是利用你現有的_destroy方法最簡單的方法,可以說在視圖中,當您顯示相關的評論和你想允許用戶刪除他們,你可以簡單地添加這樣的事情: <%除非comment.new_record? %>
謝謝!我只是將我的代碼添加到我的問題中。請看例子部分。你如何修改這個以實現複選框刪除多個記錄的方法,並添加註釋方法? – MKK 2012-07-11 01:59:22