[英]How to add attributes to a active record result in Rails 4?
可以說我有一個名為User的模型。 如何在生成的查詢的最終結果中添加虛擬屬性?
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
在我的控制器內部
@user = User.main_selection
@attributes = User::ATTRIBUTES
在視圖內,我想在表格中顯示它
<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>
唯一的問題是,我需要將balance屬性添加到生成的結果中,以便使用u [a]的循環可以工作。
我需要提到的是,可以通過@ user.first.balance調用balance,但是在循環內部不起作用,而是顯示nil值。
嘗試使用u.send(a)
代替u[a]
u [a]僅適用於屬性。 在您的示例中,balance不是屬性,而是方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.