Jump to content

The ultimate community for Ruby on Rails developers.


Photo

Null Design pattern and Active Record

ActiveRecord Design Pattern

  • Please log in to reply
1 reply to this topic

#1 bardia_1

bardia_1

    Passenger

  • Members
  • 1 posts

Posted 07 December 2013 - 05:10 PM

I have two tables.  Users, and Stats.

 

A stat for a user may exist without  the user having signed up for the app.

 

This scenerio throws an nil / NoMethod Error

 

Stat.first.user

 

From what I've read, the Null Design pattern is a great remedy for this problem. However, I don't quiet get the how to implement this solution.

 

Here's a thread on stack overflow I found that talks about it

 

http://stackoverflow...ide-on-sub?rq=1

 

but it doesn't explain how can one go about accessing the relationship of a non existent user

 

 

ie. 

 

Stat.first.user

 

with the same exact syntax. From what I've gathered, I'd have to do something like

 

Stat.first.null_user

 

Which makes my whole endeavor useless.

 

 

Help?

 

Thanks in advance.

 



#2 stevieing

stevieing

    Dispatcher

  • Members
  • 40 posts

Posted 09 December 2013 - 10:48 AM

Based on the information you have given the relationship should be the other way around.

 

It sounds like Stat should belong to the User. In the case of an anonymous User you should user User.new.stat.build

 

The only problem will be if you need to save it to the database as you won't be able to retrieve the Stat for an anonymous user.

 

Hope that helps

Steve.






0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users