0

有人可以帮我弄清楚在我点击保存后如何更新 current_price 列吗?我正在尝试将 Hotwire 与我的 rails 应用程序一起使用,当我最初从表单中保存数据时,它工作正常,但是当我尝试更新数据后,它会欺骗一切

这是我的 stock.rb 模型

class Stock < ApplicationRecord
  belongs_to :portfolio

  
  after_create_commit {broadcast_prepend_to "stocks"}
  after_update_commit {broadcast_replace_to "stocks"}
  after_destroy_commit {broadcast_remove_to "stocks"}

  before_save do 
    stock = self.ticker
    @iex_current = Faraday.get("https://cloud.iexapis.com/stable/stock/#{stock}/quote?token=key")
    @iex_body = JSON.parse(@iex_current.body)
    self.trade_price = @iex_body['latestPrice']
    self.current_price = @iex_body['latestPrice']
  end


end

和我的股票部分

<%= content_tag :tr, id: dom_id(stock) do %>

  <tr>
  <td><%=stock.created_at.strftime("%m/%d/%y")%></td>
  <td><a data-bs-toggle="collapse" href="#<%=stock.ticker%>" role="button" aria-expanded="false" aria-controls="collapseExample"><%= stock.ticker %></a></td>
  <td><%= stock.current_price%></td>
  
  
  <td><%= stock.pnl %></td>
  <td><a href="#"onclick="return false;" data-toggle="popover"data-content="<%=stock.note%>">Notes</a></td>
  <td><%= link_to "Edit", edit_stock_path(stock) %> / <%= link_to 'X', stock, method: :delete, data: { confirm: 'Are you sure?' } %></td>
  </tr>
<script>
  $(document).ready(function(){
  $('[data-toggle="popover"]').popover();
  
  });
</script>

<div class="collapse" id="<%=stock.ticker%>">
<div class="market-new">
<ul class="text-white">
<li><p>Cost/Share: <%=stock.trade_price%></p></li>
<li><p>Quantity owned: <%=stock.qty%></p></li>
<li><p>Portfolio: <%=stock.portfolio_id%></p></li>
</ul>


</div>

而我试图做的是将以下内容添加到控制器索引方法中,该方法将在加载索引页面时更新 current_price 列,但它所做的只是欺骗每一行然后消失......id喜欢在更新时更改它页面加载到按钮点击更新,但我什至无法弄清楚这个?

 @stocks = Stock.all
    @stocks.each do |a|
      @iex_current = Faraday.get("https://cloud.iexapis.com/stable/stock/#{a.ticker}/quote?token=key")
      @iex_body = JSON.parse(@iex_current.body)
      Stock.find_by(ticker: @iex_body['symbol']).update(current_price: @iex_body['latestPrice'])
      Stock.find_by(ticker: @iex_body['symbol']).update(pnl: (a.qty * a.current_price) - (a.qty * a.trade_price))
      Stock.find_by(ticker: @iex_body['symbol']).update(note: "from the controller punk")
    end
4

0 回答 0