I have a controller for customer. In the new action, I redirect to another page, which belong to the pages controller
class CustomersController < ApplicationController
class PagesController < ApplicationController
@customer = Customer.new
**Customer** Name: ___________ Email: __________ Password: _______ [Submit] **Agent** Name: ___________ Email: __________ Password: _______ [Submit]
You have a few options here to avoid your guilty feeling in the Rails controllers:
newaction of its relevant controller. The downside is a page load to change between the two options. This is the simplest, plainest choice … if you can get the boss to agree to the UX. PS: if you are using turbolinks, then the 'feel' of this option in the browser will be not far from option (2).
Keep in mind that you will have difficultly dealing with error conditions and messages with option (4). You can do it, but the code won't be simple or easy to maintain.
If option (4) is a must, one simplification can be the
create actions on each of the controllers rendering their own
new in case of an error. If you submit the 'Agent' form from your starting page, with errors, to the Agents→create action, that action finishes with a
render 'new' to show the user the Agents→new page. No 'customer' form is visible. You could then add a sprinkle of option (3) in there with a "Not an Agent? Register as a Customer." link under the form. Doing this greatly simplifies your error handling.
Which then leads to a suggestion for your original problem. Cheat. Don't have an
@customer instance variable for the
new actions (or the
registration action). Use partials for the customer and agent forms, and pass in a new object to
<%= render 'customers/new_form' %> <%= render 'agents/new_form' %>
<%= render 'customers/new_form' %>
<% form_for Customer.new do |f| %> <%# include the inputs shared with the edit action %> <%= render 'fields', f %> <%= f.submit %> <% end %>
<%# 'f' is one of the locals passed to the partial %> <% f.input_field :name %> <% f.email_field :email %> <% f.password_field :password %>
<% form_form @customer do |f| %> <%= render 'fields', f %> <%= f.submit %> <% end %>
… then you would follow the same pattern for: