如何制作辅助方法来检查对象的存在状态?

时间:2016-09-25 06:29:07

标签: ruby-on-rails ruby-on-rails-4 acts-as-paranoid

我使用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;

我的问题是......

  • 我的代码出了什么问题?以及如何解决它?
  • 总的来说,我的方法是否被认为是处理这种情况的好方法?

1 个答案:

答案 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