Search code examples
ruby-on-railsvalidationruby-on-rails-4simple-form-for

Single Page Multiple Model and Validation Rails 4.2


I have be trying to get Rails 4 to display multiple form from difference models with validations. the view renders fine will all the forms but when the form is submitted and contents error i rendered back the index action and the its shows

First argument in form cannot contain nil or be empty

My controller

def index
    @oneWay = OneWay.new
    @twoWays = TwoWay.new
end

def one_way
    @form = OneWay.new(one_params)

   if @form.valid?
   else
    render :index
    end
end

My View

 <%= simple_form_for @twoWays, url: fleet_return_path, as: 'two_way',    validate: true do |f| %>

I have tried

<%= simple_form_for @twoWays, url: fleet_return_path, as: 'two_way',    validate: true do |f| %>

but it renders but but without validation errors.

route

constraints(FleetSubdomain) do
  namespace :fleet, path: '/' do
    get '/' => 'fleet#index', as: 'index'
    post 'one_way' => 'fleet#one_way',  :as => 'one_way'
    post 'return' => 'fleet#returning',  :as => 'return'
  end

 end

Solution

  • Need to add place to show errors eg. From http://ruby.railstutorial.org/book/ruby-on-rails-tutorial

    /app/views/shared/_error_messages.html.erb

     <% if object.errors.any? %>
      <div id="error_explanation">
       <div class="alert alert-error">
         The form contains <%= pluralize(object.errors.count, "error") %>.
       </div>
      <ul>
       <% object.errors.full_messages.each do |msg| %>
        <li>* <%= msg %></li>
       <% end %>
     </ul>
    </div>
    <% end %>
    

    Your View

    <%= simple_form_for @twoWays, url: fleet_return_path, as: 'two_way',    validate: true do |f| %>
          <%= render 'shared/error_messages', object: f.object %>
    <% end %>