私は Rails4 を使用しています。また、ビューで削除された依存関係を処理するためにActsAsParanoidを使用しています。
order.rb
class Order < ActiveRecord::Base
...
has_many :ice_creams
accepts_nested_attributes_for :ice_creams
validates :user, :shift, :discount, :total, :total_after_discount, :paid, :remaining, presence: true
...
end
ice_cream.rb
class IceCream < ActiveRecord::Base
...
belongs_to :sauce, with_deleted: true
belongs_to :order
validates :size, :basis, :flavors, :ice_cream_price, :extras_price, :total_price, presence: true
...
end
アプリ/ビュー/注文/show.html.erb
...
<ul>
...
<li>Total:<%= @order.total %><li>
</ul>
<% @order.ice_creams.each do |ice_cream| %>
...
<ul class=leaders>
<li>Ice Craem Id:<%= ice_cream.id %></li>
<li>Sauce:<%= ice_cream.sauce.present? ? ice_cream.sauce.name : "Deleted Value!" %></li>
...
<% end %>
...
ソフト削除した場合sauce
ActsAsParanoid
、それを削除し、ビューが壊れないように保存します。そして、このpresent?
方法は完全に削除するのに役立ちましたがsauces
、ご覧のとおり、 anyではsauces
オプションです。ice_cream
ice_cream
sauce
deleted value
そのため、アイスクリームにソースがないか、ソースが削除されているかを判断するためのロジックをさらに考え出す必要がありました。だから私はこのヘルパーメソッドを書きました。
application_helper.rb
def chk(obj, atr)
if send("#{obj}.#{atr}_id") && send("#{obj}.#{atr}.present?")
send("#{obj}.#{atr}.name")
elsif send("#{obj}.#{atr}_id.present?") and send("#{obj}.#{atr}.blank?")
"Deleted Value!"
elsif send("#{obj}.#{atr}_id.nil?")
"N/A"
end
end
そして、使用...
アプリ/ビュー/注文/show.html.erb
...
<%= chk(ice_cream, sauce %>
...
しかし、それは戻ったNoMethodError in Orders#show
未定義のメソッド `atr' for #< IceCream:0x007fcae3a6a1c0 >
私の質問は...
- コードの何が問題になっていますか? そしてそれを修正する方法は?
- 全体として、私のアプローチはそのような状況を処理するための良い習慣と考えられていますか?