2016-09-25 32 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

感謝的人,這工作。 –