简体   繁体   中英

How to add attributes to a active record result in Rails 4?

Lets say that I have a model with name of User. How can I add a virtual attributes to the final result of generated query ?

class User < ActiveRecord::Base
  ATTRIBUTES = %w[name email balance]
  scope :main_selection, -> { select('name,email,total_bought, total_deposit') }

  def balance 
     (total_deposit - total_bought).round 
  end
end

and inside my controller I have

@user = User.main_selection
@attributes = User::ATTRIBUTES

Inside the View I would like to show it in a table

<table>
 <thead>
  <tr>
   <% @attributes.each do |a| %>
    <th><%= a %><th>
   <% end %>
  </tr>
 </thead>
 <tbody>
  <% @user.each do |u| %>
   <tr> 
    <% @attributes.each do |a| %>
     <td><%= u[a] %><td>
    <% end %>
   </tr>
  <% end %>
 </tbody>
<table>

The only problem is that I need to add the balance attribute into the generated result, so that the loop with u[a] could work.

I need to mention that the balance can be called by @user.first.balance, but inside the loop does not work and it shows a nil value instead.

Try u.send(a) instead of u[a]

u[a] will only work on attributes. In your example, balance is not an attribute, it's a method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM