Topic: how to assign object to User when Order is placed

I have Orders has_many Line_Items => belongs_to Lead

I have Users (devise) and a HABTM model for Users_leads with the right fields in the table.

I want to create a relationship between the User checking out and the Lead being purchased.  I have a after_save method setup in the Order model for this purpose.  I just don't know how to write the method:

def assign_lead_to_user
    self.line_item.lead.users_leads
     #NEEDs TO CREATE THE RELATIONSHIP BETWEEN EACH LEAD being purchased and the Current User
   save!
  end 

This will later be used to reference current_user.leads.each do |lead| in the customers account.

ideaS?

Re: how to assign object to User when Order is placed

As you Order has_many LineItems, you have 'line_items' method to get a line items collection:

self.line_items

and not 'self.line_item as you put.  So you will have to process an Array of items.

Second, Rails suppose the name of a HABTM model  in the alphabetic order, in you case it would be 'leads_users' instead of 'user_leads'.
Post your models classes to see the relations and be able to be more useful.

Last edited by Javix (2012-05-21 09:33:41)

Re: how to assign object to User when Order is placed

That helped me with another issue I had with the naming convention.  Thanks.

This is what I am attempting. 

def assign_lead_to_user
   self.line_items.each do 
     leads_users = LeadsUsers.create :user_id => :user_id, :lead => line_item.lead.id
     leads_users.save
   end   
  end 

it is returning an error on line_item.  Not sure how to run this block and call the instance of line_item to set the relationship.