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 %>
...

ソフト削除した場合sauce ActsAsParanoid、それを削除し、ビューが壊れないように保存します。そして、このpresent?方法は完全に削除するのに役立ちましたがsauces、ご覧のとおり、 anyではsaucesオプションです。ice_creamice_creamsaucedeleted 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' for #< IceCream:0x007fcae3a6a1c0 >

私の質問は...

  • コードの何が問題になっていますか? そしてそれを修正する方法は?
  • 全体として、私のアプローチはそのような状況を処理するための良い習慣と考えられていますか?
4

1 に答える 1

0

申し訳ありませんが、全体的な状況をまだよく理解していないため、より良い解決策があるかもしれませんが、現時点では提案できません。

あなたの現在のコードの問題点は、あなたの呼び出し方だと思いますchk。そのはず

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

2 番目の引数は文字列インスタンス (またはシンボル) であることに注意してください。

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
于 2016-09-25T07:28:20.440 に答える