Not sure if I’m even close to the mark on this. Ruby noob here…RACKIN
M’BRAINS HERE!!
I am trying to check values of an array against another value.
Unfortunately, I keep getting a TypeError that says:
can’t convert User into Integer
I am trying to check if a logged in user has access to a course id based
on ownership assignments.
I have 2 tables having M:M relationship and a join table:
*
Courses *
*
*
Courses_Users *
*
*
Users *
*
…and here is my action
def user_assigned_course(course_id, user_id)
allowed_users = Course.find_by_id(course_id).users
allowed_users.each do |user|
if allowed_users[user] == user_id
return true
end
end
end
Ooops: forgot to add “.id” after “allowed_users[user]”
…and here is my action
def user_assigned_course(course_id, user_id)
allowed_users = Course.find_by_id(course_id).users
allowed_users.each do |user|
if allowed_users[user] == user_id
return true
end
end
end
…help…
def user_assigned_course(course_id, user_id)
allowed_users = Course.find_by_id(course_id).users
allowed_users.each do |user|
if allowed_users[user].id == user_id
return true
end
end
end
Ooops: forgot to add “.id” after “allowed_users[user]”
…and here is my action
def user_assigned_course(course_id, user_id)
allowed_users = Course.find_by_id(course_id).users
allowed_users.each do |user|
if allowed_users[user] == user_id
return true
end
end
end
…help…
def user_assigned_course(course_id, user_id)
allowed_users = Course.find_by_id(course_id).users
allowed_users.each do |user|
if allowed_users[user].id == user_id
return true
end
end
end
ooopsblush
this worked:
def user_assigned_course(course_id, user_id)
allowed_users = Course.find_by_id(course_id).users
for user in allowed_users
if user.id == user_id
return true
end
end
end
def user_assigned_course(course_id, user_id)
allowed_users = Course.find_by_id(course_id).users
for user in allowed_users
if user.id == user_id
return true
end
end
end
And if you want to make your code a little bit cleaner, you can take
advantage of Ruby’s Enumerable#any? method:
Confidentiality Notice: This email message, including any attachments,
is for the sole use of the intended recipient(s) and may contain
confidential and/or privileged information. If you are not the intended
recipient(s), you are hereby notified that any dissemination,
unauthorized review, use, disclosure or distribution of this email and
any materials contained in any attachments is prohibited. If you receive
this message in error, or are not the intended recipient(s), please
immediately notify the sender by email and destroy all copies of the
original message, including attachments.
Wow, thanks guys! I better read up on making my Ruby code more
efficient…
You’re welcome. It really helps to browse the docs (e.g.
ruby-doc.orc/core) to see what’s in. Especially the Array, Hash,
String, Enumerable contain a lot of shortcuts.