1
我是一名初學者,他使用Rails 4.2.1和Postgresql創建一個像Yahoo Finance一樣的個人股票投資組合。去「portfolio /:id」應該爲每個投資組合顯示下面的show.html.erb文件。每個投資組合都與持股表相關聯,該表包含投資組合的股票數據以及投資組合的每隻股票的多少份額。 如果用戶在同一個投資組合中有兩個相同的股票,那麼應用程序必須從這兩個行中獲得「金額」列的總和,並且除了金額的總和之外還將具有相同數據的一行。按列分組,然後在Rails中獲得另一列的總和
模式
User
has_many :portfolios
has_many :holdings
Portfolio
belongs_to :user
has_many :holdings
Holding
belongs_to :user
belongs_to :stock
belongs_to :portfolio
Stock
has_many :holdings
數據庫模式
table "holdings"
t.integer "user_id"
t.integer "stock_id"
t.integer "portfolio_id"
t.integer "amount"
end
table "portfolios"
t.integer "user_id"
t.string "name"
end
table "stocks"
t.string "symbol"
end
PortfoliosController
def show
@holdings = @portfolio.holdings # can't figure out what to do next.
end
# As it is, this just shows rows for every new holding transaction.
個show.html.erb
<% @holdings.each do |holdings| %>
<tr>
<td><%= holdings.portfolio.user.name %></td>
<td><%= holdings.portfolio.name %></td>
<td><%= holdings.stock.symbol %></td>
<td><%= holdings.amount %></td>
</tr>
<% end %>
錯誤
@holdings = @portfolio.holdings.sum(:amount, :group => "stock_id" :order=> "sum(amount) DESC")
導致此錯誤:
NoMethodError at /portfolios/22
undefined method `each' for 171:Fixnum
# And by the way, 171 is the correct sum but it needs to work with the looped table
此:
@holdings = @portfolio.holdings.group(:portfolio_id).sum(:amount)
所
導致此錯誤:
NoMethodError at /portfolios/22
undefined method `portfolio' for [22, 171]:Array
我似乎無法得到它與每個循環工作。
放哪兒你會看到這個語法'sum(:amount,:group =>「stock_id」:order =>「sum(amount)DESC」)'..我從來沒有見過它.. –
@R_O_R嘿,對不起,我lo st頁面。我已經瀏覽了數百個關於這個話題的網頁。 – anikulin
@ portfolio.holdings.group(:stock_id).select(「SUM(amount)as total,holdings。*」)。order(「total DESC」)'檢查這個 –