0

I have two models in my app: list.rb and contacts.rb, they have a has_and_belongs_to_many relationship. I have the following method in my contacts_controller.rb:

def import
  Contact.import(params[:file])
  redirect_to contacts_path, notice: "Contacts were imported."
end

I am calling his method after creating a List in the list#create action. how can I set/input the list_id into this import method above, where the records are created through a csv file?

Thank you!

AllOutOfSalt
  • 1,516
  • 3
  • 27
  • 46
Jan
  • 239
  • 1
  • 4
  • 17

1 Answers1

0

You need first get the list, like you do for example in the show method. Make sure that import is a member-route.

@list = List.find(params[:id])

You need then modify your import method, that it takes a second parameter for your list.

def Contact.import_for_list(file, list)
   # loop over csv lines
     # for each line you create a contact element
     # and then add the new contact element to the list
     list.contacts << newly_created_contact

     # or you create the contact from the list object
     list.contacts.build(....)
   # depending how you created the objects you need to save them explicitly
end

And lastly you call your modified method

def import
  @list = List.find(params[:id])
  Contact.import_for_list(params[:file], @list)
  redirect_to contacts_path, notice: "Contacts were imported."
end
Meier
  • 3,858
  • 1
  • 17
  • 46
  • Thank you for you suggestion. import is a collection of contacts, I have not gotten the csv import working otherwise. I know how to set the list according to your suggestion '@list = List.find(params[:id])' but how to I pass the list_id in since I am going over from the list model to the contacts model? I think I am getting there, I now simply just get the error that the list_id is empty. Thanks again for you help, as you can see I am very new to rails. – Jan Oct 03 '15 at 16:23