Can View call some Model methods in Rails?

erb, rails-activerecord, ruby-on-rails

Solution

Its perfectly fine to call the object-methods/attributes from the view, as long as the call would not change the data. I mean, call readers/getters. A Bad practice would be to call/invoke methods that update/delete the data. Don't call setters.

Also, if there is any complex computation involved, resort to helpers.

Problem

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 in Controller: ``` def show @products = Product.all end ``` And in View: ``` <% @products.each do |product| %> Product Name: <%= product.name %> Product Income: <%= product.income %> Product Cost: <%= product.cost %> Product Profit: <%= product.profit %> <% end %> ``` Is it a good practice to call model methods from view? When I searched for that, I found many people saying it is NOT a good practice to ever call model methods or access DB from views. And on the other hand, some others said that don't call class methods or any method updates the DB from view but you can access any method that only retrieve data. Then, is this code a good practice?

Original source