我正在使用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>
我的问题是...
- 这有什么错我的代码?以及如何解决它?
- 总体而言,我的方法是否被认为是处理这种情况的良好实践?
感谢的人,这工作。 –