【问题标题】:How can I verify a user doesn't exist before shoveling the user in?在铲入用户之前如何验证用户不存在?
【发布时间】:2018-10-20 21:53:51
【问题描述】:

Rails 新手,请多多包涵……

我创建了一个日历应用,日历的所有者可以将其他用户添加到日历中。我刚刚意识到他们可以多次添加同一个用户,这显然是我不想要的。我尝试了很多不同的方法,包括检查模型内部的方法,但没有奏效……我正在使用包含来验证……

我的控制器中的当前方法是:

def update
  if @calendar.calendar_admin?(current_user)
    @new_user = User.find(params[:calendar][:user_ids])
    if @calendar.users.includes(@new_user)
      redirect_to user_calendar_path(@calendar), notice: 'This user has already been added to this calendar.'
    else
      @calendar.users << @new_user
      if @calendar.save
        redirect_to user_calendar_path(@calendar), notice: 'Your calendar has been updated.'
      else
        redirect_to user_calendar_path(@calendar)
      end
    end
  end
end

结束

无论如何,即使用户没有,它也会卡在“此用户已添加到此日历中”。我正在铲除新用户,但我什至不确定这是否是添加新用户的正确方式?

输入?

【问题讨论】:

  • 应该是include? 而不是includes

标签: ruby-on-rails duplicates include exists verification


【解决方案1】:

您想使用include? 而不是includes

include? 根据集合是否包含特定项目返回布尔值。 includes 是一种不同的方法,它会返回一个非空值,它是真实的。

【讨论】:

  • 好的,我也试试这个!我以为我已经先尝试过了。我尝试了很多东西,很难跟上。
  • 我一定没有尝试过,因为它有效!耶耶!快乐的舞蹈时间。
【解决方案2】:

您想测试@calendar.users 是否已包含特定用户。不幸的是,includes 听起来不错,但它用于添加表/模型以加入结果(如果我尝试运行您的线路,它会爆炸)。

所以我建议以下替代方案:

if @calendar.users.to_a.any{|uu| uu.id == @new_user.id}

这将获取数组中的所有用户并检查是否存在具有相同 id 的用户。这很容易理解,但不是最优的,因为它可能会检索大量数据。

可能更好的选择是使用数据库,并计算是否链接了具有您想要的 id 的用户:

 if @calendar.users.where("users.id" => @new_user.id).count > 0 

【讨论】:

  • 所以这将作为一种方法进入我的模型,因为它是 activerecord?还是我完全不在了?
  • 或者用 find_or_initialize_by 代替铲子怎么样?
猜你喜欢
  • 2020-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-06
  • 1970-01-01
相关资源
最近更新 更多