Ask A Question

Notifications

You’re not receiving notifications from this thread.

First argument in form cannot contain nil or be empty

Nathan La Barbera asked in Rails

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 :rage:

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! :joy:

Nathan

Reply

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

Reply

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

Reply

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

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 86,946+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.