views:

249

answers:

1

Hi, I have tried to set up a separate section of my app using a subdirectory called controlpanel to manage various parts of the site.

I've set up the namespace in my routes.rb

map.namespace :controlpanel do |submap|
    submap.resources :pages
    # other controllers
end

And placed the controller and views into the relevant subdirectories.

Controlpanel::PagesController

  def new 
    @page = Page.new
  end

  def create
    if @page = Page.create_with_author(current_user, params[:page])
      flash[:notice] = 'Page was successfully created.'
      redirect_to ([:controlpanel, @page])
    else
      render :action => 'new'
    end
  end

Using this mixed in class method

def create_with_author(author, params)
    created = new(params)
    created.author = author
    if created.save
      created
    end
  end

And the view (controlpanel/pages/new.html.erb renders a partial called _form

<%= render :partial => 'form' %>

Which is as follows:

<% semantic_form_for([:controlpanel, @page]) do |form| %>
    <% form.inputs do %>  
    <%= form.input :title %>
    <%= form.input :body %>
    <% end %>
    <%= form.buttons %>
  <% end %>

If I fill in the form correctly, it works as expected, redirecting me to the new page, however, if I leave fields blank, violating the validation constraints, I get the following error:

RuntimeError in Controlpanel/pages#create

Showing app/views/controlpanel/pages/_form.html.erb where line #1 raised:

Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id

Can anyone see what is going wrong?

I'm using the formtastic plugin to create the form, but it still happens if I use a regular form.

Any advice greatly appreciated.

Thanks.

+2  A: 

Given that the create action is called and new is rendered, Page.create must evaluate to nil.

You probably want to pass params[:page] to create.

Leventix
Sorry, I missed that bit in my post. I do have it in the code though.
Dan
Do you use ActiveRecord for the page model? The documentation says that `create` should always return an object.
Leventix
I'm actually using a mixin to save the current user as the author. Sorry, I've added that above now too.
Dan
OK, then just make sure the `create_with_author` returns the page object in any case.
Leventix
Ah right, I see the problem now. Thanks for your help.
Dan