Reputation: 27232
I have 2 different models called Parent
and Child
.
I have a page called House
that has the link_to
to both forms on it:
pages/house.html.erb
link_to "Parent", new_parent_path
link_to "Child", new_child_path
When you start on the page it is empty with no forms.
I want to be able to click the new_parent
link and generate the parent form on the same page but if I click the new_child
link I want to remove the parent form and replace it with the child form by AJAX. How would I do this?
Upvotes: 0
Views: 165
Reputation: 27232
This was actually very simple to create. This question and this one helped me understand AJAX and jquery better.
Lets use the parent as an example:
I put the format.js
in my controller for the new
action:
ParentsController
def new
@parent = Parent.new
respond_to do |format|
format.js
end
end
I delete my parents/new.html.erb
as a personal choice and replace it with new.js.erb
that will be called by my "Parent" link_to
.
# parents/new.js.erb
$("#generate-form").html("<%= escape_javascript(render(:partial => 'parents/form', locals: { parent: @parent })) %>");
Then create a Parent form in a partial that is remote => true
for AJAX.
# parents/_form.html.erb
<%= form_for(@parent, :remote => true) do |f| %>
<%= f.input :full_name %>
<%= f.button :submit, 'Done' %>
<% end %>
Then I have one page that holds both forms.
PagesController
def index
respond_to do |format|
format.html
end
end
Then the links on that page for both parent and child.
#pages/index.html.erb
<li><%= link_to "Parent", new_parent_path, :remote => true %></li>
<li><%= link_to "Child", new_child_path, :remote => true %></li>
<div id="generate-form">
</div>
The remote => true
of my links and form will respond to the js
format of my new
action and my div id="generate-form"
acts as the boss, placing either form partial inside of it. This automatically replaces one with the other depending on the link you click, thus resulting in changing forms dynamically.
Note: The code for the child model is the same (except for form fields). Just replace the Model name (Parent to Child).
Upvotes: 0
Reputation: 24350
I think it will be easier to do it without Ajax, but with css. Generate the 2 forms in the page (using partials for example), and put than inside an hidden div (css style: display: none
), and use javascript with your links to show/hide the div containing the form you want to display (with JQuery show and hide effects)
Upvotes: 4