I'm going crazy trying to get this to work. I want to loop through a jointable called TriggersUser to see where the user doesn't have a Trigger record (there are only 3 triggers they can have)
if current_user.triggers.any?
(1..2).each do |n|
if !current_user.triggers.find(n)
@next_trigger = Trigger.find(n)
else
@next_trigger = Trigger.find(3)
end
end
end
I get this error: Couldn't find Trigger with 'id'=1 [WHERE "triggers_users"."user_id" = ?]
which is perfect, because the user does not have an associated record with trigger_id 1 in the join table. BUT, I want it to now declare a variable @next_trigger = Trigger.find(1)
What am I missing?
TY!!
You should use find_by_id
instead of find
.
find_by_id
simply returns nil
when a record does not exist for a given id.
If you use find
, then you need to handle the exception. You can do this:
@next_trigger = Trigger.find(n) rescue nil
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.