Kirk
Kirk

Reputation: 159

Create a model while in another controller

I have a simple address book page that lists entries and has an 'Add Profile' button under tabs for different models.

Let's say this page is at Dashboard#AddressBook. Within this page I want the Add Profile button to load the form for Individuals#New, and allow it to submit without switching pages.

The Individual model calls submodels like Address, which have preset options and thus require a variable to be set in the controller.

Using AJAX and a modal seems the correct approach, but I'm unable to find a working example that will let me utilize a RESTFUL controller for a model that's being created from a page within another controller.

How can I create a model while on a page for a different controller?

Upvotes: 0

Views: 708

Answers (2)

Martin M
Martin M

Reputation: 8638

It's no problem, to have multiple forms for different controllers on one page:

<%= form_for @address do |f| %>
...
<% end %>

<%= form_for Article.new do |f| %>
...
<% end %>

I understand, that your problem is, how to pre load the 'new' object for the 'foreign' controller.
I like the appoach with AJAX and lazy loading tabs:

<div id="tabs">
  <ul>
    <li><a href="#tabs-1">Own models form</a></li>
    <li><a href="<%= new_article_path %>">new Articel</a></li>
  </ul>
  <div id="tabs-1">
    <%= render "form"
  </div>
</div>

selecting the second tab new Article calls Article#new where you can initialize that object and render the form for it.
Remember to render the action's view without a layout.

Upvotes: 1

Jake Smith
Jake Smith

Reputation: 2813

you can render the form as a partial, and apply the option remote: true. This will go to the create action of the other controller and you will need to add format.js to the respond_to block. Then make a file named create.js.erb in the /views/profiles directory. This is where you will use jQuery to change your view to render the new information you just created.

Upvotes: 1

Related Questions