Neal Neal - 7 months ago 11
Ruby Question

Using variable within each function to sort_by

At the moment i'm playing around with Rails to get the hang of it and coding in general. Therefore I created my first rails app in which I want to display my games (from the game database) on one of the pages and sort them by a variable calculated within the each function. My view page looks like this (simplified):

<% @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 %>


I get how i can order them by game.userexp1 or game.price but I can't figure out if it is possible to sort them by @FinalScore (without also putting the userexpscore and pricescore in the database). I was wondering if this is possible and if yes how I can do that.

Thanks in advance!

Answer

View is not proper place for business logic.

You can move score calculating logic into model, e.g.:

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

Then in view

<% @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 %>

I suggest you read about MVC and separation of concerns

Comments