假设您将模型称为“主题”作为父模型,将“评论”模型作为子模型。在 url 'topics/show/35' 上,您可以看到属于该主题 ID#35 的所有评论。
当登录的用户想在这个页面发表他的新评论时,我应该在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