【发布时间】:2012-07-11 14:25:36
【问题描述】:
假设您有一个名为“Topic”的模型作为父模型,而“Comment”模型作为子模型。 在 url 'topics/show/35' 上,您可以看到属于该主题 ID#35 的所有 cmets。
当登录用户想在这个页面发表他的新评论时, 我应该在topics_controller.rb 中写'comment_create' 动作吗? 或者只是在 cmets_controller.rb 中编写“创建”操作,然后从此页面调用它? 哪个是常规方式??
如果我在 cmets_controller 中调用 'create' 操作,我该如何在视图中写入以通过
- 要添加 cmets 的“型号名称”
- '型号 ID#'
- '评论正文'
还是应该像这样单独编写动作?
控制器/cmets_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
示例已更新!!!
views/topics/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
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 database-design