我正在使用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
但是因爲您可能會看到sauces
在任何ice_cream
中都是可選的,所以如果有任何ice_cream
沒有sauce
那麼也將顯示deleted value
。
所以我不得不想出更多的邏輯來確定是否有任何ice_cream沒有醬,或者有刪除醬。所以我寫了這個幫手方法。
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 %>
...
但returnd NoMethodError in Orders#show
未定義的方法`ATR」爲#<冰淇淋:0x007fcae3a6a1c0>
我的問題是...
- 這有什麼錯我的代碼?以及如何解決它?
- 總體而言,我的方法是否被認爲是處理這種情況的良好實踐?
感謝的人,這工作。 –