我正在尝试在我的数据库中实现某种唯一性,如果它已经在数据库中,则可以选择替换当前值。
我的表格似乎是
t.integer "task_id"
t.integer "accessor_id"
t.integer "access_owner"
t.boolean "access_rights"
我想检查一下如果有一个条目有task_id,accessor_id和access_owner而不是更新access_right,如果没有一个创建这样的条目
我当前的创建方法和新方法是
class AccessorsController < ApplicationController
def new
@accessor = Accessor.new
@task_id = params[:task_id]
end
def create
@accessor = Accessor.new(accessor_params)
@user = User.where(email: params[:accessor][:accessor_id]).first
@accessor.accessor_id = @user.id
@accessor.access_owner = current_user.id
respond_to do |format|
if @accessor.save
format.html { redirect_to Task, notice: 'User was successfully created.' } #
format.json { render action: 'show', status: :created, location: Task }#
else
format.html { render action: 'new' } #
format.json { render json: @accessor.errors, status: :unprocessable_entity }#
end
end
end
我尝试了以下
@accessor = Accessor.where("access_owner = ? AND accessor_id = ? AND task_id = ?", current_user.id, User.where(email: params[:accessor][:accessor_id]).first,params[:task_id]).first || Accessor.new(accessor_params)
但它无效
答案 0 :(得分:1)
您可以使用find_or_initialize_by..
方法:
@accessor = Accessor.find_or_initialize_by_task_id_and_accessor_id_and_access_owner(params[:task_id], params[:accessor_id], params[:access_owner])
@accessor.update_attributes(
:access_rights => params[:access_rights]
)