First let me explain an example:
In Model :
class Product < ActiveRecord::Base has_many :line_items def income self.line_items.sum(:price) end def cost self.line_items.sum(:cost) end def profit self.income - self.cost end end
Then to the controller :
def show @products = Product.all end
And in the view:
<% @products.each do |product| %> Product Name: <%= product.name %> Product Income: <%= product.income %> Product Cost: <%= product.cost %> Product Profit: <%= product.profit %> <% end %>
Is it good to use model methods for viewing ?
When I looked for this, I found that many people say that it is not good practice to ever call model methods or access a database from views.
And, on the other hand, some others said that do not call class methods or any method updates the database from the view, but you can access any method that only retrieves data.
Then, is this code good practice?
source share