stig Garet
stig Garet

Reputation: 564

Verify if relation was saved or deleted

I would like to check if a relation was saved directly into the controller. But currently I cannot find the solution

My code :

@ut = UsersTask.where(task_id: @task.id).where(user_id: @user.id).delete_all
if @ut.destroyed?
  @task.update(effectif: (@task.effectif -= 1))
end

Upvotes: 0

Views: 33

Answers (2)

JaMes
JaMes

Reputation: 607

You can make something like that :

respond_to do |format|
  if @task.users.include?(@user)
    format.js {render inline: "location.reload();" }
  else
    UsersTask.where(task_id: @task.id, user_id: @user.id).first_or_create
    @task.update(effectif: (@task.effectif += 1))
    format.js 
  end
end

Upvotes: 1

MrShemek
MrShemek

Reputation: 2483

delete_all returns a number of affected rows. I think it will be enough to compare @ut.count with the return of delete_all. Simply assign those two values to variables and compare them:

@ut = UsersTask.where(task_id: @task.id).where(user_id: @user.id)
@tasks_to_delete = @ut.size
@deleted_tasks = @ut.delete_all

if @tasks_to_delete.eql?(@deleted_tasks)
  @task.update(effectif: (@task.effectif -= 1))
end

Or, if you do not want to load UsersTasks into @ut, you can do:

users_task_number = UsersTask.count
@ut = UsersTask.where(task_id: @task.id).where(user_id: @user.id).delete_all
if UsersTask.count.eql?(users_task_number - @ut)
  @task.update(effectif: (@task.effectif -= 1))
end

Upvotes: 0

Related Questions