1

做到这一点的最佳方法是什么?

@user = UserFinder.find(first_name: "Dave")
if !@user
  return render :text => '// No user named Dave found'
end

if @user.last_name != "Edwards"
  # This is not the guy we want
  @user.destroy

  # Now we want to re-execute the search again forever until we find Dave Edwards
end

请记住,这是我拥有的真实代码的一个非常简单的示例,所以我知道我可以首先过滤查询,但我想要这样。

我不确定如何使用beginand whileblocks 来执行此操作,因为如果我们遇到不需要的用户,则需要销毁它。

我的尝试:


begin
  @user = UserFinder.find(first_name: "Dave")
  return render :text => '// No user named Dave found'
end while @user.destroy if @user.last_name != "Edwards"

这不起作用,因为while块得到的结果destroy不是比较last_name

PS如果这是不可能的,如何用相同的参数重新加载Rails控制器动作?

4

3 回答 3

3

尝试这个:

begin
  @user = UserFinder.find_by_first_name("Dave")
  render :text => '// No user named Dave found' if @user.nil?
  return if @user.nil?
end while @user.last_name != "Edwards" && @user.destroy
于 2012-10-26T12:15:41.313 回答
0
user.destroy while user = UserFinder.where(:first_name => "Dave",  :last_name => "Edwards").first
于 2012-10-26T13:35:42.000 回答
0

这对你有用吗?

while (@user = UserFinder.find(first_name: "Dave")) and @user.last_name != "Edwards"
  @user.destroy
end

if @user
  render ...
else
  render :text => '// No user named Dave found'
end
于 2012-10-26T12:12:01.927 回答