Forum: Ruby on Rails Accessing results of retrieve where

Be2b7277cff8516117cbd7a33df7b03a?d=identicon&s=25 Dave Castellano (dcastellano1)
on 2014-01-30 04:18
Hi,

I am searching for a record using "where":

@profile = Profile.where(:user_id => current_user.id)

This returns:
=> [#<Profile id: 6, user_id: 19, last_subject_id: 6, last_book_id: 2,
last_chapter_id: 1, last_section_id: 1, last_subsection_id: 1,
last_minisection_id: 20, about: nil, image: nil, created_at: "2013-03-13
01:45:44", updated_at: "2014-01-30 02:11:54", students_last_subject_id:
6, students_last_book_id: nil, students_last_chapter_id: nil>]

I am trying to then access "students_last_subject_id" using several
methods including @profile.students_last_subject_id,
but it keeps returning nil.  With the enclosing brackets i am guessing
this is not a hash, but I also cannot access it as an array .

Can anyone help?

Thanks,

Dave
A47e0a6beeb9d048ff054fc1c3a97418?d=identicon&s=25 Walter Davis (walterdavis)
on 2014-01-30 07:06
(Received via mailing list)
On Jan 29, 2014, at 10:18 PM, Dave Castellano wrote:

> 01:45:44", updated_at: "2014-01-30 02:11:54", students_last_subject_id:
> 6, students_last_book_id: nil, students_last_chapter_id: nil>]
>
> I am trying to then access "students_last_subject_id" using several
> methods including @profile.students_last_subject_id,
> but it keeps returning nil.  With the enclosing brackets i am guessing
> this is not a hash, but I also cannot access it as an array .
>
> Can anyone help?

Where always returns an array (sometimes it's empty). If you want to get
the record (or nil) you can use Profile.find(current_user.id) instead.
That will return the bare object (not wrapped in an array) and you can
get the attributes out of it. If you want to use where(), then do this:

@profile = Profile.where(:user_id => current_user.id).first

Walter
Be2b7277cff8516117cbd7a33df7b03a?d=identicon&s=25 Dave Castellano (dcastellano1)
on 2014-01-30 23:53
Thanks!!

Dave
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.