Can I see the invocation of some model methods in Rails?

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?

+6
source share
2 answers

It's nice to call object methods / attributes from a view until the call changes the data. I mean, readers / recipients of calls. Bad practice would be to call / call methods that update / delete data. Do not call setters.

Also, if there is any complicated computation, consult your helpers.

+8
source

Since your methods should gain access to the line_items association in order to avoid a problem with N + 1 and calling DB queries from the view, I would advise getting your line_items in the show using include:

 def show @products = Product.includes(:line_items) end 

With this setting, I think it’s normal to call these methods in sight.

+3
source

Source: https://habr.com/ru/post/959157/


All Articles