如果为true,我如何分配条件(查询),如果条件为假,如何进行另一项赋值?

时间:2012-12-04 20:26:22

标签: ruby-on-rails ruby

如何避免输入

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

2 个答案:

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