如何避免输入
TypeOfVoyagePortActivity.find_by_description(activity_description)
两次?
这是我在其中使用它的上下文:
if TypeOfVoyagePortActivity.find_by_description(activity_description)
pl.activity = TypeOfVoyagePortActivity.find_by_description(activity_description)
else
pl.activity = TypeOfVoyagePortActivity.find_by_description("Custom")
end
答案 0 :(得分:5)
model = TypeOfVoyagePortActivity
pl.activity = model.find_by_description(activity_description) ||
model.find_by_description("Custom")
答案 1 :(得分:1)
您可以将find_by_description
的结果分配给变量
if t = TypeOfVoyagePortActivity.find_by_description(activity_description)
pl.activity = t
else
pl.activity = TypeOfVoyagePortActivity.find_by_description("Custom")
end
或者作为更好的选择:
p1.activity = [activity_description, "Custom"].each_with_object(nil) do |a, memo|
memo ||= TypeOfVoyagePortActivity.find_by_description(a)
end