Skip to main content

First argument in form cannot contain nil or be empty

Rails • Asked by Nathan La Barbera

Alright everyone, I would greatly appreciate your help solving this problem. Here is what I'm attempting to do; I have an articles controller and all the related views to create new article posts.

Articles Controller:

class ArticlesController < ApplicationController
  def index
    @articles = Article.all
  end
  def new
    @article = Article.new
  end
  def create
    @article = Article.new(
      title: params[:article][:title],
      body: params[:article][:body])
    @article.save
    redirect_to article_path(@article)
  end
 def show
    @article = Article.find(params[:id])
  end
end

This controller works fine when I go to a form that was generate by the scaffolding. I can navigate to articles/new and then fill the form out for a new article and it posts perfectly. Here is my dilemma, I have a separate view and controller for an admin page, and I want to be able to copy the form from the articles/new view into that admin/index view. For some reason I am having an issue posting to another controller from a separate view. Can someone please shed light on this, after spending countless hours over this weekend, you can imaging how frustrating this is getting

Admin Index:

<%= form_for @article do |f| %>
  <ul>
  <% @article.errors.full_messages.each do |error| %>
    <li><%= error %></li>
  <% end %>
  </ul>
  <p>
    <%= f.label :title %><br />
    <%= f.text_field :title %>
  </p>
  <p>
    <%= f.label :body %><br />
    <%= f.text_area :body %>
  </p>
  <p>
    <%= f.submit %>
  </p>
<% end %>

Admin Controller:

class AdminController < ApplicationController
  def index
    render layout: "admin_layout"
  end
end

The error sign that I am getting when I navigate to localhost:3000/admin/index is: First argument in form cannot contain nil or be empty

Any help I could get from you more experience would be amazing. Thank you a ton in advanced!

Nathan


In your admin controller you need to instantiate @article in your Admin Controller's index action. Something like this: @article = Article.order('created_at DESC') or simply @article = Article.all if you don't care about the order it should default to sorting by .id


James, you are exactly correct. Thank you for the feedback and helping me.


Not a problem, glad I could help! Let me know if you need anymore help.


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 27,623+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.