2016-09-25 57 views
0

我正在使用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 %> 
... 

如果我删除了一个sauceActsAsParanoid软删除它并保存我的看法从打破。并且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>

我的问题是...

  • 这有什么错我的代码?以及如何解决它?
  • 总体而言,我的方法是否被认为是处理这种情况的良好实践?

回答

0

对不起,我还不完全理解整个情况,所以可能有更好的解决方案,但现在我不能提出它。

你现在的代码有什么问题我想你是怎么拨打chk的。 应该

... 
<%= chk(ice_cream, 'sauce') %> 
... 

注意,第二个参数是一个字符串实例(也可能一个符号)。

而且我觉得你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逻辑。

UPDATE

也许这将是清洁这样

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 
+0

感谢的人,这工作。 –