我使用Rails4,并使用ActsAsParanoid处理我视图中已删除的依赖项。
order.rb
Already up-to-date.
ice_cream.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
应用/视图/命令/ show.html.erb
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
如果我删除了...
<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
。
所以我不得不想出更多的逻辑来确定冰淇淋是否没有酱汁,或者是否有酱油。所以我写了这个辅助方法。
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&#39;对于#&lt; IceCream:0x007fcae3a6a1c0&gt;
我的问题是......
答案 0 :(得分:0)
抱歉,我还不太了解整个情况,所以可能有更好的解决方案,但现在我无法提出建议。
您认为当前代码有什么问题我打电话给您chk
。
它应该是
...
<%= chk(ice_cream, 'sauce') %>
...
请注意,第二个参数是一个String实例(或者它可以是一个Symbol)。
我认为你的chk
方法应该是这样的
def chk(obj, atr)
attribute_id = obj.send("#{atr}_id")
attribute = obj.send(atr)
if attribute_id && attribute.present?
attribute.name
elsif attribute_id.present? and attribute.blank?
"Deleted Value!"
elsif attribute_id.nil?
"N/A"
end
end
我只是重构了你的方法,所以它应该在语法上是正确的。但我还没有检查所有if
逻辑。
<强>更新强>
也许这样会更干净
def chk(obj, attr)
attr_id = obj.send("#{attr}_id")
attr_obj = obj.send(attr)
if attr_id.present?
attr_obj.present? ? attr_obj.name : 'Deleted Value!'
else
'N/A'
end
end