0

In my rails user model, I am trying to write a method which will return a list for the current time frame, and in the absence of a list for that time frame, create one which is associated with the user and then return it:

class User < ActiveRecord::Base

def todaysList
   today = Time.new
   if self.lists.where(:date => today.to_date)
      return self.lists.where(:date => today.to_date).first #Get the object, not the ActiveRecord::Relation
   else
      self.lists.create!(:date => today.to_date) #Make the list, return it!
   end
end

My question is, why is it that when I call self.lists.create!(:foo => 'bar'), the user association is not populated?

I've decided to get around this a more sloppy way, by explicitly assigning the user in the create! call, as such:

self.lists.create!( :date => today.to_date, :User_ID = self.id)

however this solution just doesn't seem right.

Thanks in advance and apologies as always for stupid, redundant or badly worded questions.

2
  • The code you've shown should be setting the user_id on the list it creates. What are you seeing that makes you think it's not? Commented Sep 16, 2011 at 20:37
  • I can tell it isn't populating by looking at the resulting object in the rails console. There is an index view for lists which shows the current list, and each time the view is called, it calls the todaysList method in the user model, finds no list associated with the current user which meets the requirements, then creates a new one. So each time I refresh the list index view, the ID of the current list increments. Weird. Commented Sep 16, 2011 at 21:13

1 Answer 1

1

I would do something like this:

def todays_list
  lists.find_or_create_by_date(Date.today)
end

The method name change is just preference.

Sign up to request clarification or add additional context in comments.

1 Comment

Very cool. This is much cleaner, obviously. Calling this from the user model as 'self.lists.find_or_create_by_foo('bar') still doesn't populate the user association, but that can be done easily by specifying :creator in the call to the finder. I'm still very interested in finding out why self.create doesn't populate the user association. I'm sure theres a reason, even though it seems unintuitive to me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.