【发布时间】: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。
我尝试了很多不同的方法,但似乎无法正常工作。
【问题讨论】:
-
State和User有什么关系?基于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