Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can View call 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 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?

like image 966
Mahmoud Khaled Avatar asked Dec 02 '13 10:12

Mahmoud Khaled


People also ask

What's the purpose of ActiveRecord?

Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database. It is an implementation of the Active Record pattern which itself is a description of an Object Relational Mapping system.

Can we call controller method in model rails?

As the two answers said, you should not be calling controller methods from your models. It is not recommended.

What is ActiveRecord in Rails?

What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.


1 Answers

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.

like image 192
Satya Kalluri Avatar answered Nov 14 '22 21:11

Satya Kalluri