简体   繁体   中英

Rails 3 update two models using ajax

I've been stuck on this for about 2 weeks. I need help in the proper way to do this. I have two models. Model one is Leads. Model two is Referrals.

Leads belongs_to referrals

Referrals has_many Leads

In the Lead entry screen there is a partial that displays possible Referrals for the lead to select from. There is an Add Referral link in the partial that brings up a modal using twitter bootstrap as the css framework. From that I am rendering the New action of the Referral controller.

This all works up to this point. What I want to have happen is that I can then enter a new referral, it is saved, the modal closes, and the list of referrals in the partial of the Leads edit/new view is then updated to reflect the new referral that has been added. But at this point I now have nested form_for's. As well as a Referral form that is working off a different controller.

I am not sure how I should approach this. I have been searching and trying various methods for a couple of weeks now. Do I repeat myself and completely rebuild the Referral view and controller under the Leads controller and view? Repetitive code like that is why I switched to rails, and why I feel I'm not looking at this correctly. There has to be a simple way around this. I have looked at using Gems like Draper and Cell, and I've read up on using presenters. But those seem to all be solutions for a dashboard type of view, not what I am trying to accomplish.

Any help or direction would be much appreciated.

Thank you...

This is the way i program this kind of problem.
It works for me, maybe you can adapt to your own situation.

Well, you create action on yout Referral Controller should respond with javascript.

if @referral.save
    format.js

This way, you will have a create.js.erb file whitin the views folder where you keep your referral's views.
In the create.js.erb you may have something similar to this:

$('#modal_id').hide(); // Hide the modal or if you prefer, remove from DOM.
$('#referral_list_id').chidren().delete(); // Remove the list of referrals.
$('#referral_list_id').html(
  "<%= escape_javascript(render('referrals_list')) %>"
); // Render a partial with the new content from your controller.

Your form for a new referral inside your modal, should be remote too:

<%= form_for @referral, :remote => true do %>

Maybe you will run into some gotchas while implementing this way, but i believe it is kinda easy to solve.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM