的数据库设计的动作假设你有所谓的“主题”作为父母的模型,“评价”作为一个孩子。 在网址'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