I have an Order, which belongs to a Buyer. Part of the order#form
allows the user to enter the email address of the buyer. If they email
address doesn't exist in the system, then a Buyer record is created in
a before_save filter.

The weird thing is I have to explicitly set the buyer_id field in a
callback filter. That's telling me that I'm either doing something
wrong, or Rails isn't doing what it should. Here's the sanitized code:

class Order < ActiveRecord::Base
  attr_accessor :ordered_by

  belongs_to :user
  belongs_to :buyer, :class_name => "User", :foreign_key => "buyer_id"

  before_save :assign_buyer_by_email

  private

  def assign_buyer_by_email
    self.buyer = User.find_by_email(ordered_by)
    if buyer.nil?
      self.buyer = User.create(:email => ordered_by)
      # snip
      self.buyer_id = self.buyer.id # Won't work without this line,
seems un-DRY or worse
    end
  end
end

ordered_by is the email address on the order#form. You'll notice buyer
shares the table with user. To head off questions about
find_or_create_by, I have other things do to the new user where you
see snip, and it also results in the user being created but the
buyer_id is not set.

Can someone explain what's happening here?

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to