views:

27

answers:

1

I have the following:

class Invite < ActiveRecord::Base
  belongs_to :user
  has_many :invite_recipients
  has_many :recipients, :through => :invite_recipients
end

class InviteRecipient < ActiveRecord::Base
  belongs_to :invite
  belongs_to :user_comm

  validates_associated :user_comm, :invite
  validates_uniqueness_of :user_comm_id, :scope => :invite_id
end

class UserComm < ActiveRecord::Base
end

I'd like to create a method for Invite with invite_text and a list of UserComms as the variables and then have it create a new invite with the following validations:
1. All UserComms are unique
2. The invite isn't saved unless all the associated InviteRecipients are saved as well (in other words, the invite isn't valid unless all the created InviteRecipients are valid)

I'm not familiar with how to create model functions. Moreover, when I try something like this:

i = Invite.new(:invite_text => 'come join')
ir1 = InviteRecipient.new(:invite => i, :user_comm => user_comm1)
ir2 = InviteRecipient.new(:invite => i, :user_comm => user_comm2)
i.invite_recipients = [uc1, uc2]
i.save!

I get: SystemStackError: stack level too deep

A: 

You need use i.recipients not invite_recipients! Like this:

i.recipients.create(:user_comm => user_comm1)
i.recipients.create(:user_comm => user_comm2)
huacnlee
actually, that doesn't work either, but this does: i.recipients << user_comm1. Still, the problem with this is that i can't then set any of the attributes on the InviteRecpient.
Paul