0

In our Rails 4 app, there are four models:

class User < ActiveRecord::Base
  has_many :administrations, dependent: :destroy
  has_many :calendars, through: :administrations
end

class Administration < ActiveRecord::Base
  belongs_to :user
  belongs_to :calendar
end

class Calendar < ActiveRecord::Base
  has_many :administrations, dependent: :destroy
  has_many :users, through: :administrations
end

class Post < ActiveRecord::Base
    belongs_to :calendar
end

We have routed the corresponding resources with Routing Concerns, as follows:

concern :administratable do
  resources :administrations
end

resources :users, concerns: :administratable
resources :calendars, concerns: :administratable

To create a new @calendar, we use the following form:

<h2>Create a new calendar</h2>
<%= form_for(@calendar) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>
  <div class="field">
    <%= f.text_field :name, placeholder: "Your new calendar name" %>
  </div>
  <%= f.submit "Create", class: "btn btn-primary" %>
<% end %>

When we embed this form into the user's show.html.erb (so that a user can create a new calendar from his profile), everything works fine.

However, we would like to have a special page, call dashboard, where a user could see all his calendars and create a new one.

We believe the logical url should be /users/:id/administrations.

So, we embedded the above form in the Administration's index.html.erb.

And as soon as we do that and visit for instance /users/1/administrations, we get the following error:

ArgumentError in AdministrationsController#index

First argument in form cannot contain nil or be empty

Extracted source (around line #432):

else
  object      = record.is_a?(Array) ? record.last : record
  raise ArgumentError, "First argument in form cannot contain nil or be empty" unless object
  object_name = options[:as] || model_name_from_record_or_class(object).param_key
  apply_form_for_options!(record, object, options)
end

EDIT: here is also our Administrations#Controller:

class AdministrationsController < ApplicationController

  def to_s
    role
  end

  def index
    @user = current_user
    @administrations = @user.administrations
  end

  def show
    @administration = Administration.find(params[:id])
  end

end

Any idea of what we are doing wrong?

Thibaud Clement
  • 6,607
  • 10
  • 50
  • 103

1 Answers1

1

First argument in form cannot contain nil or be empty

The reason is @calendar is not initialised in your controller action, so obviously @calendar is nil. So is the error.

To get your form to work in administrations/index.html.erb, you should be having the below code in your index action of your administrations_controller.

def index
  @user = current_user
  @administrations = @user.administrations
  @calendar = Calendar.new # this one.
end
Thibaud Clement
  • 6,607
  • 10
  • 50
  • 103
Pavan
  • 33,316
  • 7
  • 50
  • 76