【问题标题】:How to check if a record exists for just a specific user?如何检查是否仅存在特定用户的记录?
【发布时间】:2018-08-31 16:29:34
【问题描述】:

现在在我的 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。

我尝试了很多不同的方法,但似乎无法正常工作。

【问题讨论】:

  • StateUser 有什么关系?基于scope 的验证可能更有意义,但我需要了解这种关系以解释将其放在哪里。类似于validates :user_id, uniqueness: { scope: :state_name } 或相反的validates :state_name, uniqueness: { scope: :user_id } 或使用连接表validates :state_id, uniqueness: {scope: :user_id}

标签: sql ruby activerecord sinatra


【解决方案1】:

你想要的是……

  if @state.users.include? current_user
    "You have already added this state."
  else

【讨论】:

  • 为什么需要重新保存@state@state.users &lt;&lt; current_user 添加到 JOIN 表中;这已经保留了更改。
猜你喜欢
  • 1970-01-01
  • 2018-09-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-17
  • 2019-04-07
  • 1970-01-01
  • 1970-01-01
  • 2021-01-16
相关资源
最近更新 更多