0

UserNotification belongs_to User and User has_many UserNotification.

I am trying to access the notifications through the user. If I run in the console:

User.find(31).user_notifications

It returns the following user:

<Employer id: 31, email: "person1@commercial.com", ...>

The code above is correct (A user can be of type 'employer' or 'freelancer'. I believe this is called polymorphic). However, if I run:

User.where(email: 'person1@commercial.com').user_notifications

I am told that:

undefined method `user_notifications'

This should give me the same user as the 'find' method I use above. In my application, I am having the same problem referring to the user_notification when using current_user. For example, I have:

@notifications = current_user.user_notifications.inspect

I do this while logged in as the same user I was working with in the console, User 31. However, the user_notifications are displayed as nil.

How do I access user_notification through current_user?

tereško
  • 58,060
  • 25
  • 98
  • 150
Philip7899
  • 4,599
  • 4
  • 55
  • 114
  • Thanks, that worked for the console problem. Why is that? I definitely only have one user with that email address? – Philip7899 Dec 11 '13 at 20:02

1 Answers1

1

.where returns an array. So when you use it you need to specify which result you want:

User.where(email: 'person1@commercial.com').first.user_notifications

See this question for a detailed explanation:Rails .where vs .find

Community
  • 1
  • 1
RustyToms
  • 7,600
  • 1
  • 27
  • 36
  • Thanks, how do i get it to work in the application with current_user? – Philip7899 Dec 11 '13 at 20:03
  • I think you would have to provide more code, like how do you return `current_user`? If you get `current_user` by using `where` it is the same situation. – RustyToms Dec 11 '13 at 20:05
  • I'm not sure, current_user is a helper from devise. – Philip7899 Dec 11 '13 at 20:06
  • That is very strange, if you are using devise it should work without `.first`. The only thing I can think is that when you call current_user you haven't saved the model with the `user_notifications` property yet, so it doesn't exist yet. – RustyToms Dec 11 '13 at 20:09