提前抱歉这个非常简单的问题,但在检查条件的同时设置变量的最佳方法是什么。例如,我有:
@friends = []
@user.facebook_friends.each do |key,value|
if test = Authorization.includes(:user).find_by_uid(key) != nil
@friends << {"name" => test.user.name, "facebook_image_url" => test.user.facebook_image_url}
end
end
当我拉入授权记录时,我试图引入用户记录,以便最小化我的数据库查询。我知道我不能写
test = Authorization.includes(:user).find_by_uid(key) != nil
以设置测试变量。编写此代码以使其正常运行的最佳方法是什么?
答案 0 :(得分:3)
你只需要parens:
(test = Authorization.includes(:user).find_by_uid(key)) != nil
此外,还有更多的rails方式:
unless (test = Authorization.includes(:user).find_by_uid(key)).nil?
@friends << {"name" => test.user.name, "facebook_image_url" => test.user.facebook_image_url}
end