Search code examples
ruby-on-rails-5argument-error

Argument error when trying to create a mission


I have a form for creating new Missions with an Admin account. Each Mission is linked to an account. When I visit admin/missions/new I get an error "ArgumentError in Admin::Missions#new". Can anyone point to what I'm doing wrong?

When I checked the rails console a mission id and name does show up, but I guess I'm missing the Admin for the mission.

Here's my Controller

class Admin::MissionsController < Admin::ApplicationController
  def index
    @missions = missions
  end

  def new
    @mission = current_account.missions.new(params[:mission])

    @mission.save

  end

  def create
    render plain: params[:mission].inspect
  end


  def edit
    @mission = missions.find(params[:id])
  end




  private

  def missions 
    @missions ||= current_account.missions
  end
end

Here's my form

<%= form_with [:admin, @mission] do |f| %>
  <div>
    <label>Name</label>
    <%= f.text_field :name %>
  </div>

  <div>
  </div>

  <div>
    <%= f.submit %>
  </div>

<% end %>

I'm expecting the url admin/missions/new to take me to the form, but I I get the argument error wrong number of arguments (given 1, expected 0)


Solution

  • You don't have params yet in the new action as the view (where the form which has to collect the params is) is rendered after the controller code. The object should be created in the create action:

    def create
      current_account.missions.create(params[:mission])
    end
    

    And the new action should be just:

    def new
      @mission = current_account.missions.new
    end
    

    Check the Binding a Form to an Object section of the Rails guide.

    The form code seems also to be wrong, as form_with [:admin, @mission] do |f| is not a valid syntax. It should be:

    <%= form_with model: [:admin, @mission] do |form| %>
    

    Check form_with documentation for more details.