简体   繁体   中英

how to add form to application.html.erb page ruby

I'm quite new to ruby and I'm trying to put the form to add a new post to the "application.html.erb" page.

Somehow I can't get it to work by just copying the code from the "app/views/things/_form.html.erb" page, and also I can't seem to get it to work by copying the code from the "app/views/things/new.html.erb" page.

If I do that I get the error:

First argument in form cannot contain nil or be empty

The error points towards:

<%= form_for(@thing) do |f| %>

This is a code that I find in the "app/views/things/_form.html.erb" page.

Can anybody point me in the right direction? To be honest, I don't even know where to start looking for the answer.

The @thing should be initialized in your controller. I suppose you've got a things_controller.rb that has a new action in it. In this action, controller should initialize @thing and therefore it is visible in app/views/things/new.html.erb .

You really shouldn't put forms in application.html.erb , but just to make the error disappear, you could do

<%= form_for(Thing.new) do |f| %>

(assuming you've got a Thing model in app/models/thing.rb ).

This way you'll initialize an instance of Thing right in your application.html.erb view.

I think you should take a look at ruby on rails MVC model first, and also go through a basic tutorial. Just a quick review of you question:

  1. application.html.erb is usually in the layout folder of rails, it's job is to provide a root template/layout for the whole project if not specified. usually you don't want to put any code that is not commonly needed by all pages.

  2. the reason it is giving you the error First argument in form cannot contain nil or be empty is because, the helper method form_for is expecting the controller to provide a @thing to the view file application.html.erb , in your case, it is obvious that @thing is not exist in your controller or your ApplicationController .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM