在我的 Rails 7 應用程式中,我有要裝飾的資料表。資料來自 API 回應,因此實際上它是一個哈希陣列。如下所示:
# transactions_controller.rb
class TransactionsController < ApplicationController
def index
response = client.transactions.list(platform_id: current_user.platform_id, page: 1, per_page: 100)
@transactions = response.body['data']
end
private
def client
@client ||= TestAPI::Client.new
end
end
現在在 transactions/index.html.erb 里面我有一個表格,@transactions里面有我想要裝飾的資料:
#views/transactions/index.html.erb
<table class="table table-striped">
<thead>
<tr>
<b>
<tr>
<th>Date</th>
<th>Amount</th>
</tr>
</b>
</tr>
</thead>
<tbody>
<% @transactions.map do |transaction| %>
<tr>
<td>
<%= transaction['created_at'] %>
</td>
<td>
<%= transaction['amount_cents'] %>
</td>
</tr>
<% end %>
</tbody>
</table>
我知道我可以將該邏輯注入到視圖檔案中,如下所示:
(...)
<td>
<%= Date.parse(transaction['created_at']).strftime("%d.%m.%Y") %>
</td>
<td>
<%= "#{ transactions_data.last['amount_cents']/100}" "#{ transactions_data.last['currency']}" %>
</td>
(...)
但是我想從視圖中擺脫這種邏輯,因為將來我會在這里有越來越多的邏輯。
uj5u.com熱心網友回復:
希望從視圖中洗掉邏輯的榮譽。
你需要一個新物件,它可以被呼叫TransactionPresenter或任何你選擇的物件。它將實作視圖邏輯。所以在你的TransactionsController:
def index
response = client.
transactions.
list(platform_id: current_user.platform_id, page: 1, per_page: 100).
map{|t| TransactionPresenter.new(t)}
@transactions = response.body['data']
end
TransactionPresenter模型可能是這樣的:
class TransactionPresenter
def initialize(transaction)
# capture the fields of interest as variables
end
def amount
"$#{amount_cents.to_f/100}" # for example, whatever makes sense in your context
end
end
所以所有邏輯都從視圖中洗掉:
<table>
<% @transactions.each do |transaction| %>
<tr><%= transaction.amount %></tr>
<% end %>
</table>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/505036.html
上一篇:將價格更改為另一個值RoR
