更新时间:2023-11-18 21:34:10
您可以执行以下操作:
# activites/index.html.erb
<% @activities.each do |activity| %>
# etc.
<%= render "comments/comments", comments: activity.comments %>
<%= render "comments/form" %>
<% end %>
# comments/_comments.html.erb
<% comments.each do |comment| %>
# your code to display each comment
<% end %>
您可以看到我向render
方法传递了一个参数:
You can see that I passed an argument to the render
method:
render "comments/comments", comments: activity.comments
它将给_comments
部***部变量comments
,它等于activity.comments
.
It will give to the _comments
partial the local variable comments
which will be equal to activity.comments
.
您甚至可以使用form
部分执行几乎相同的操作:
You can even do the almost-same-thing with the form
partial:
# activites/index.html.erb
<%= render "comments/form", new_comment: Comment.new(commentable_id: activity.id, commentable_type: activity.class.model_name) %>
# comments/_form.html.erb
<% form_for new_comment do |f| %>
此外,Ruby on Rails中的一个好习惯是不要创建多个实例变量@like_this_one
.将其保持在最低限度,因为它可能会造成混淆.我还要补充一点,您的变量命名也很重要.
Also, a good practice in Ruby on Rails is to not create several instance variables @like_this_one
. Keep it to the minimum because it can be confusing. I will add that your variable naming is important too.
以下内容:
@activity = Activity.find(params[:id])
@commentable = @activity
@comments = @commentable.comments
可以重构为:
@activity = Activity.find(params[:id])
然后在您的视图中,您可以通过以下方式访问评论:
And then in your views you could access to the comments by doing:
@activity.comments