如何检查特定用户是否存在记录?

问题描述 投票:0回答:1

现在在我的POST路线中,我有这个:

post '/states' do
  if logged_in? && params[:state_name] != ""
    @state = State.find_or_create_by(:state_name => params[:state_name])
      if @state.users.exists?
        "You have already added this state."
      else
        @state.users << current_user
        redirect "/states"
       end

如果用户将相同的状态添加两次,则会收到错误消息,并且不会向数据库添加重复项。太棒了,但是当一个新用户添加相同的状态时,他们会收到相同的错误消息。如何检查记录是否仅存在于current_user?如果它不存在,我希望将current_user添加到@ states.users。

我尝试了很多不同的东西,但似乎无法让它发挥作用。

sql ruby activerecord sinatra
1个回答
0
投票

你想要的是......

  if @state.users.include? current_user
    "You have already added this state."
  else
© www.soinside.com 2019 - 2024. All rights reserved.