目前我正在使用Rails来掌握它并进行编码。因此,我创建了我的第一个rails应用程序,我想在其中一个页面上显示我的游戏(来自游戏数据库),并按照每个函数中计算的变量对它们进行排序。我的视图页面看起来像这样(简化):
<% @games.sort_by{|game| ???}.each do |game| %>
<p>Userexp: <%= game.userexp1 %></p>
<p>Userexpscore: <% if (game.userexp1 <= 60) %> <%= @UserexpScore = 1 %>
<% elsif (game.userexp1 > 60) %> <%= @UserexpScore = 2 %> = 2 <% end %></p>
<p>Price: €<%= game.price %></p>
<p>Pricescore: <% if (game.price <= 20) %> <%= @PriceScore = 2 %>
<% elsif (game.price > 20) %> <%= @PriceScore = 1 %> <% end %></p>
<p>Finalscore: <%= @FinalScore = @UserexpScore + @PriceScore %></p>
<% end %>
我知道如何通过game.userexp1或game.price来订购它们但是我无法弄清楚是否有可能通过@FinalScore对它们进行排序(没有将userexpscore和pricecore放在数据库中)。我想知道这是否可行,如果是,我怎么能做到。
提前致谢!
答案 0 :(得分:3)
查看不适合业务逻辑。
您可以将得分计算逻辑移动到模型中,例如:
class Game < ActiveRecord::Base
def userexp_score
userexp1 <= 60 ? 1 : 2
end
def price_score
price <= 20 ? 2 : 1
end
def final_score
userexp_score + price_score
end
end
然后在视图中
<% @games.sort_by(&:final_score).each do |game| %>
<p>Userexp: <%= game.userexp1 %></p>
<p>Userexpscore: <%= game.userexp_score %></p>
<p>Price: €<%= game.price %></p>
<p>Pricescore: <%= game.price_score %></p>
<p>Finalscore: <%= game.final_score %></p>
<% end %>
我建议你阅读MVC和关注点分离