ユーザーにポートフォリオがあるアプリがあります。ポートフォリオには多くのポジションがあり、各ポジションには多くの動きがあります。Railsオブジェクトにnil値を渡すとエラーが発生する
マイポートフォリオショーのページは次のように構築されています:
<p>
<strong>Name:</strong>
<%= @portfolio.name %>
</p>
<h1>Positions</h1>
<div class = 'table'>
<table>
<thead>
<tr>
<th>Name</th>
<th>Quantity</th>
<th>Stock</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody id = "positions">
<%= render @positions %>
</tbody>
</table>
</div>
<h3>New Position</h3>
<%= render 'positions/form' %>
<%= link_to 'Edit', edit_portfolio_path(@portfolio) %> |
<%= link_to 'Back', portfolios_path %>
私の位置部分が構築されています:
<tr>
<td class="col-md-1"><%= position.name %></td>
<td class="col-md-1"><%= position.quantity %></td>
<td class="col-md-1"><%= position.ticker %></td>
<td>
<%= form_for [@portfolio, position, @movement] do |f| %>
<div id = "movement-errors">
<% if @movement.errors.any? %>
<%= render 'shared/error_messages', object: @movement %>
<% end %>
</div>
<div class="field">
<%= f.label :quantity %>
<%= f.number_field :quantity, class: 'form-control' %>
</div>
<div class="actions">
<%= f.submit class: 'btn btn-primary' %>
</div>
<% end %>
</td>
</tr>
そして、私の共有のエラー部分は次のとおりです。
<% if object.errors.any? %>
<div id = "error_explanation">
<div class = "alert alert-danger">
The form contains <%= pluralize(object.errors.count, "error") %>.
</div>
<ul>
<% object.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
私が提出移動フォームの値がゼロであれば、エラーをポップアップしてユーザーにメッセージを伝えたい。私は数量の存在を確認する検証を持っています。
class Movement < ApplicationRecord
belongs_to :position
validates :quantity, presence: true
そして、私のコントローラの動き#がアクションを作成し、それが今の現状では、私は、空のフォームを送信するとき、私はbetter_errorsの宝石を使用して、このエラーが出る
class MovementsController < ApplicationController
before_action :load_portfolio_and_position
def create
@movement = Movement.new(movement_params)
@movement.position_id = @position.id
@movement.update_price
@movement.date = DateTime.now
@movement.trade ='buy'
respond_to do |format|
if @movement.save
@position.update_attribute(:quantity, (@movement.quantity + @position.quantity))
format.html { redirect_to @portfolio, notice: 'Movement was successfully created.' }
format.js
else
format.html { render template: 'portfolios/show' }
format.json { render json: @movement.errors, status: :unprocessable_entity }
format.js
end
end
end
次のようになります。
" nil 'はActiveModelと互換性のあるオブジェクトではありません。 to_partial_pathを実装する必要があります。
そして、私のポートフォリオの表示ページからrender @positions行がハイライトされています。私は部分的な道を進んでいると思った。私の構文は間違っていますか?
おそらく私は目が見えませんが、コントローラで@portfolioをどこに設定しているのか分かりません。 – David
Movementコントローラbefore_actionを表示するように編集しました。私はすべてのアクションの前に、ポートフォリオとオブジェクトの位置をつかんでいます。 –
'load_portfolio_and_position'メソッドで' @ positions'オブジェクトをつかんでいますか? –