如何在Ruby中显示全局变量内容?附Rails视图代码
如何在Ruby中显示全局变量的内容?
嘿,关于这个问题其实很简单!在Ruby(包括Rails的ERB视图)里,要显示全局变量的内容,直接输出就行——因为全局变量都是以$开头的,比如你代码里的$total,在ERB视图中用<%= %>标签包裹它就能把值渲染出来。
结合你给出的Rails视图代码,我猜你是想计算所有评论的分数总和然后展示?那我们可以把你的代码补全并优化一下:
<% if @course.comments.exists? %> <h2>Ratings</h2> <% $total = 0 %> <% @course.comments.each do |comment| %> <p> <strong>Commenter:</strong> <%= comment.commenter %> </p> <p> <strong>Score:</strong> <%= comment.score %> </p> <p> <strong>Comment:</strong> <%= comment.comment %> </p> <p> <strong>Words in Comment:</strong> <%= comment.comment.split.size %> </p> <%# 把每个评论的分数累加到全局变量里 %> <% $total += comment.score.to_i %> <% end %> <%# 这里就是显示全局变量$total的地方 %> <div style="margin-top: 1rem; padding: 0.5rem; background: #f5f5f5;"> <strong>Total Score:</strong> <%= $total %> </div> <% end %>
不过这里必须给你提个醒:在Rails开发里,尽量别用全局变量!全局变量会在整个应用的请求周期里共享状态,很容易出现意外的bug——比如多个用户的请求互相干扰,导致$total的值混乱。
更优的做法是用局部变量或者实例变量,比如把$total换成局部变量total:
<% if @course.comments.exists? %> <h2>Ratings</h2> <% total = 0 %> <% @course.comments.each do |comment| %> <!-- 评论内容输出 --> <p> <strong>Commenter:</strong> <%= comment.commenter %> </p> <p> <strong>Score:</strong> <%= comment.score %> </p> <p> <strong>Comment:</strong> <%= comment.comment %> </p> <p> <strong>Words in Comment:</strong> <%= comment.comment.split.size %> </p> <% total += comment.score.to_i %> <% end %> <div style="margin-top: 1rem; padding: 0.5rem; background: #f5f5f5;"> <strong>Total Score:</strong> <%= total %> </div> <% end %>
要是想更贴合Rails的MVC设计原则,最好把计算逻辑放到控制器里。比如在你的CoursesController的对应action(比如show)里:
def show @course = Course.find(params[:id]) # 直接用ActiveRecord的sum方法计算总分,高效又简洁 @total_score = @course.comments.sum(:score) end
然后在视图里直接用<%= @total_score %>就能显示总分了,这样视图里只负责渲染,逻辑都放在控制器里,代码更清晰也更容易维护。
内容的提问来源于stack exchange,提问作者Gabe Ruiz
相关产品推荐
相关产品推荐

