Chazu
Chazu

Reputation: 1018

Calling ActiveRecord::Create() from within rails user model not associating new object with user

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.

Upvotes: 0

Views: 1118

Answers (1)

natedavisolds
natedavisolds

Reputation: 4295

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.

Upvotes: 1

Related Questions