Rails 4: Receiving the following error: First argument in form cannot contain nil or be empty - ruby

I am receiving the following error on a project of mine: First argument in form cannot contain nil or be empty. I am trying to create an edit page for my code. Fairly new with Rails and trying to learn without scaffolding.
Controller:
class BooksController < ApplicationController
def new
#book = Book.new
#authors = Author.all
end
def edit
#book = Book.find(params[:id])
end
def show
#Notice how the #books is plural here.
#books = Book.all
#authors = Author.all
##books = Book.where(id: params[:id])
end
#Create method will save new entries
def create
#book = Book.new(book_params)
#authors = Author.all
if #book.save
flash[:success] = "Book Added to Databse!"
redirect_to #book
else
render 'new'
end
end
private
#Note that this method will go up into the create method above.
def book_params
params.require(:book).permit(:title, :pub_date, :publisher, :author_id)
end
end
Model Page: (For Book)
class Book < ActiveRecord::Base
validates :title, :pub_date, :publisher, presence: true
validates :title, uniqueness: true
belongs_to :author
end
Model Page: (For Author)
class Author < ActiveRecord::Base
validates :name, presence: true
validates :name, uniqueness: true
has_many :books
end
Edit page:
<h1>Update a book entry</h2>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<%= form_for(#book) do |f| %> **ERROR SEEMS TO BE RIGHT HERE!!!**
<%= render 'form' %>
<div class="form-group">
<%= f.label :title %>
<%= f.text_field :title, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.label :pub_date %>
<%= f.text_field :pub_date, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.label :publisher %>
<%= f.text_field :publisher, class: 'form-control' %><br />
</div>
<div class="form-group">
<%= f.select(:author_id,
#authors.collect {|a| [ a.name, a.id ]},
{:include_blank => 'Please select an author'},
class: "form-control") %><br />
</div>
<%= f.submit 'Save Changes', class: "btn btn-primary" %>
<% end %>
</div>
</div>
Render form page (_form.html.erb)
<% if #book.errors.any? %>
<div id="error_explanation">
<div class="alert alert-danger">
<h2><%= pluralize(#book.errors.count, "error") %>
prohibited this entry from being saved:</h2>
<ul>
<% #book.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
</div>
<% end %>
SHOW PAGE:
<div class="move">
<h1>Showing Book Titles:</h1>
</div><br />
<div class="row">
<% #books.each do |book| %>
<div class="col-md-4">
<div class="panel panel-default">
<div class="panel-body">
<h2><%= book.title %></h2>
<h2><%= book.publisher %></h2>
<h2><%= book.pub_date %></h2>
<h2><%= book.author.name %></h2>
<h2><%= link_to "Edit", edit_path, class: "btn btn-primary" %>
</div>
</div>
</div>
<% end %>
Here is my Log telling me what is wrong:
Started GET "/edit" for ::1 at 2015-08-14 16:49:17 -0400
Processing by BooksController#edit as HTML
Rendered books/edit.html.erb within layouts/application (2.2ms)
Completed 500 Internal Server Error in 9ms (ActiveRecord: 0.0ms)
ActionView::Template::Error (First argument in form cannot contain nil or be empty):
3: <div class="row">
4: <div class="col-md-6 col-md-offset-3">
5:
6: <%= form_for(#book) do |f| %>
7: <%= render 'form' %>
8:
9: <div class="form-group">
app/views/books/edit.html.erb:6:in `_app_views_books_edit_html_erb___525891009649529081_70260522100960'
I will say that I have deleted the first 14 books from my data base and so the first book start on ID 14. Not sure if that matters.
Finally, I have tried adding all of these different instance variables to my controller in the edit method:
##book = Book.where(id: params[:id])
##book = Book.find_by_id(params[:id])
##book = Book.all
##book = Book.find_by_id(params[:id])
#book = Book.new(book_params)
#When I use the two below lines,
there are no error pages but create a new entry.
##book = Book.new
##authors = Author.all
Any Help will be appreciated! Thank you for your time!!!

This error means that the first argument to form_for is a nil value (in this case #book). Most of the times I've seen this, it's due to malformed controller actions, but that doesn't look to be the case here. From what I can tell, it's one of two things:
You're trying to edit a Book that doesn't exist. Do a .nil? check on it before deciding to render the form, and render an error message (or redirect) instead.
Your routes are broken, and the edit action is not rendering the edit view. This is most likely not the case.
EDIT:
After updating with your template for show, this looks like your problem:
<%= link_to "Edit", edit_path, class: "btn btn-primary" %>
I see two problems with this (though I'll need to see the output of rake routes to verify). Firstly, you need to pass an argument to the edit path (without them, where would your params come from?). Secondly, the default route for this would be edit_book_path.
Try this:
<%= link_to "Edit", edit_book_path(book), class: "btn btn-primary" %>

Assuming book ID 14 is in your database, you should be able to navigate to localhost:3000/books/14/edit if you created it with something like resources :books (documentation here). If this doesn't work, either your routes are not defined correctly or book with ID 14 does not exist in your database.
On your show view, change the link_to line to:
<%= link_to 'Edit', edit_book_path(book), class: "btn btn-primary" %>
So two changes:
Again, assuming book is a Restful resource, when you run rake_routes, you should see the path to edit is edit_book_path.
You need to pass the book instance with the path so Rails knows which object you wish to edit.
I found the correct syntax here.
Hope this helps.

Related

Ruby on rails 4: showing error messages

I have trouble displaying error message for invalid inputs using Ruby on rails. If anyone can help me with it? Currently new to the area.
I suspect the area is due to :user and #user.
This is my form generated on index.html.erb
<%= form_for :user, url: '/login', html:{id:"form"} do |f| %>
<h2 class="login">Login</h2>
<div class="form">
<input type="name" placeholder="Name" name="user[name]" class="form-input" required /></div>
<% end %>
My ActiveRecord Model:
class User < ActiveRecord::Base
validates :name, :uniqueness => true
has_secure_password
end
I try to use the following error handling, by passing the following code after <%= form_for :user, url: '/login', html:{id:"form"} do |f| %> but it did not work with and showed:
NoMethodError in Users#register
: undefined method `errors' for nil:NilClass
<% if #user.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#article.errors.count, "error") %> prohibited this article from being saved:</h2>
<ul>
<% #user.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
You should be able to do something like this.
/app/views/shared/_error_messages.html.haml:
- if object.errors.any?
.alert.alert-danger
The form contains #{pluralize(object.errors.count, "error")}.
%ul#error_explanation
- object.errors.full_messages.each do |msg|
%li= msg
Then, wherever you want errors to be shown in your views, something like:
= render 'shared/error_messages', object: f.object
Note object in the method. When you call, you could pass either an object instance from your controller or (in the above case), the object of a form builder.

How to solve ParameterMissing error using ROR

Please help me to solve the below error.
Error:
ActionController::ParameterMissing in CustmersController#create
param is missing or the value is empty: users
When i am submitting the data,this error is coming.
My code is as follows
views/custmers/new.html.erb
<h1>Enter your data here</h1>
<center>
<%= form_for #users,:url => {:action => 'create'} do |f| %>
<% if #users.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#users.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% #users.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<label for="name">Name:</label>
<%= f.text_field :name,placeholder:"Enter your name",:class => "input-field" %>
</p>
<p>
<label for="email">Email:</label>
<%= f.email_field :email,placeholder:"Enter your email",:class => "input-field" %>
</p>
<p>
<label for="phone">Phone no:</label>
<%= f.telephone_field :phoneno,placeholder:"Enter your phone number",:class => "input-field" %>
</p>
<p>
<%= f.submit "Submit" %>
</p>
<% end %>
<%= link_to "BACK",custmers_index_path %>
</center>
controller/custmers_controller.rb
class CustmersController < ApplicationController
def index
end
def new
#users=Custmer.new
end
def show
end
def create
#users=Custmer.new(user_params)
if #users.save
flash[:notice]="You have signed up successpully"
flash[:color]="valid"
redirect_to :action => 'index'
else
flash[:alert]="You have not signed up successfully"
flash[:color]="invalid"
render :new
end
end
private
def user_params
params.require(:users).permit(:name,:email,:phoneno)
end
end
model/custmer.rb
class Custmer < ActiveRecord::Base
EMAIL_REGEX = /\A[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\z/i
validates :name,presence:true,length: { minimum: 5 }
validates :email, :presence => true, :uniqueness => true, :format => EMAIL_REGEX
validates :phoneno, presence: true,length: {minimum: 10}
end
I am using rails version-4.2.0 and ruby version-1.9.3.Please help me to resolve this error.
If you look at the stack trace accompanying your error, you could tell definitely where the problem is -- look for the first line in the stack trace that refers to your code (and not library code).
But a fair guess is the require(:users) line in your controller. It looks like you either copy/pasted this code from another controller, or changed the name of your controller after generating it as part of your scaffold.
It should be requires(:custmer) instead, as that is the class of the thing you're submitting.
As a general approach, you should follow the standard Rails practices for naming things, throughout. If you really want to use the misspelled, Custmer class, have at it, but use #custmr inside your controller and views to refer to an instance, not #users.

RoR: How can I get my microposts to show up?

Here is the users show view where they are supposed to show up. ..
<section>
<div id= "purchases">
<%= render 'shared/micropost_form_purchase' %>
</div>
<div id="sales">
<%= render 'shared/micropost_form_sale' %>
</div>
</section>
<%= #sales %> <%# This is just to see if it outputs anything. It doesn't :( %>
<div id="purchases list">
<ol class="microposts">
<%= render #purchases unless #purchases.nil? %>
</ol>
</div>
<div id="sales list">
<ol class="microposts">
<%= render #sales unless #sales.nil? %>
</ol>
</div>
so the forms (partials) are loading fine, but then when I make a post, in either one, neither the purchases list nor the sales list shows up. I checked the database and they are being created along with an entry in the column indicating kind (either sale or purchase).
Here are the forms:
<%= form_for (#micropost) do |f| %>
<div class="field no-indent">
<%= f.text_area :content, placeholder: "What's something else you want to buy?" %>
<%= hidden_field_tag 'micropost[kind]', "purchase" %>
</div>
<%= f.submit "Post", class: "btn btn-large btn-primary" %>
<% end %>
and
<%= form_for (#micropost) do |f| %>
<div class="field no-indent">
<%= f.text_area :content, placeholder: "What's something else you want to buy?" %>
<%= hidden_field_tag 'micropost[kind]', "sale" %>
</div>
<%= f.submit "Post", class: "btn btn-large btn-primary" %>
<% end %>
also, here is the show part of the users_controller.rb
def show
#user = User.find(params[:id])
#micropost=Micropost.new
#microposts = #user.microposts.paginate(page: params[:page])
end
and here is the show part of the microposts_controller.rb
def show
#micropost = Micropost.find(params[:id])
#microposts = Micropost.where(:user_id => #user.id)
#purchases= #microposts.collect{ |m| m if m.kind == "purchase"}.compact
#sales = #microposts.collect{ |m| m if m.kind == "sale"}.compact
end
additionally, with the help of this post (http://stackoverflow.com/questions/12505845/ruby-error-wrong-number-of-arguments-0-for-1#12505865) the variables #microposts, #purchases, and #sales are all outputting correctly in the console.
can anyone help me out?
edit: using scopes as suggested by the answer given works in the console (it outputs everything correctly, but they still don't show up in the view. Does this mean it is something wrong with my syntax for the users show page?
edit 2:
Here is the view/microposts/_micropost.html.erb code
<li>
<span class="content"><%= micropost.content %></span>
<span class="timestamp">
Posted <%= time_ago_in_words(micropost.created_at) %> ago.
</span>
<% if current_user?(micropost.user) %>
<%= link_to "delete", micropost, method: :delete,
confirm: "You sure?",
title: micropost.content %>
<% end %>
</li>
I'm making some assumptions without seeing more of your code, but it looks like you could
write what you've shown a little differently. I'm assuming your databases are migrating
and have the required columns, e.g., Micropost#kind, Micropost#user_id, etc.
You can use scopes to refine a collection of microposts more expressively. It might be helpful to read
up about ActiveRecord scopes: http://guides.rubyonrails.org/active_record_querying.html#scopes.
class Micropost < ActiveRecord::Base
belongs_to :user
scope :purchases, where(:kind => "purchase")
scope :sales, where(:kind => "sale")
# your code
end
I'm also assuming your user has many microposts:
class User < ActiveRecord::Base
has_many :microposts
# your code
end
For your forms, I'd suggest attaching your hidden field to the form object (f.hidden_field) so
you don't have to specify the name as 'micropost[kind]'.
<%= form_for(#micropost) do |f| %>
<div class="field no-indent">
<%= f.text_area :content, placeholder: "What's something else you want to buy?" %>
<%= f.hidden_field :kind, :value => "sale" %>
</div>
<%= f.submit "Post", class: "btn btn-large btn-primary" %>
<% end %>
In MicropostsController#show, you can use your new scopes:
def show
#micropost = Micropost.find(params[:id])
#microposts = #user.microposts
#purchases = #microposts.purchases
#sales = #microposts.sales
end
You should also confirm that your MicropostsController#create action is actually adding
the microposts to the user sending the form (I'm assuming a current user method).
def create
#micropost = current_user.microposts.create(params[:micropost])
# yada
end
You can also confirm expected results on rails console after creating purchases or sales micropost with:
Micropost.purchases
Micropost.sales
Again, I could be missing something without seeing more of the code base.
Check Micropost.count, #purchases.count, #sales.count (by printing them in the controller, or some part of the view) to see if the records actually exist.
Also, if you want to render collections likes #sales and #purchases, you need to make sure that the model partial exists (_micropost.html.erb in your case). That is probably where you need to look for the view errors. For all you know, that file could be empty, thus no errors will show up at all.
The problem might also lie in your microposts#create (or whichever action that you are saving the micropost in), the micropost should be associated with the current_user:
#micropost = current_user.microposts.build(params[:micropost])
Taking this and your previous question into account, I suggest you go through the original code for the RoR tutorial again (and verify that all tests are passing) before taking it apart. You can always add new tests to it for your experiments and they will help in figuring out where you went wrong.

Getting undefined method `klass' for nil:nilclass - Railscast #197

Hi all I followed Ryan Bates' railscasts on nested models and form, but I am getting getting undefined method `klass' for nil:nilclass. I am pretty sure it is due to the the link_to_add_fields since everything was working prior. Below is my error and other relevant code and I'm using Rails 3.1. I did a lot of googling and did not find any to solve my problem, so if you guys could help me out I would really appreciated it. Thanks for your help.
_form.html.erb
<%= form_for(#organization) do |f| %>
<% if #organization.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#organization.errors.count, "error") %> prohibited this organization from being saved:</h2>
<ul>
<% #organization.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div id="restaurant_field" class="field">
<%= f.fields_for :restaurants do |builder| %>
<%= render 'organizations/partials/restaurant_fields', :f => builder %>
<% end %>
</div>
<div class="actions"><%= f.submit %></div>
<% end %>
_restaurant_fields.html.erb
<p class="fields">
<%= f.label :name, "Restaurant Name" %><br />
<%= f.text_field :name %>
<%= link_to_remove_fields "Remove", f %>
application_helper.rb
module ApplicationHelper
def link_to_remove_fields(name, f)
f.hidden_field(:_destroy) + link_to_function(name, "remove_fields(this)")
end
def link_to_add_fields(name, f, association)
new_object = f.object.class.reflect_on_association(association).klass.new
fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
render(association.to_s.singularize + "_fields", :f => builder)
end
link_to_function(name, h("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")"))
end
end
application.js
function remove_fields(link) {
$(link).prev("input[type=hidden]").val("1");
$(link).closest(".fields").hide();
}
function add_fields(link, association, content) {
var new_id = new Date().getTime();
var regexp = new RegExp("new_" + association, "g");
$(link).parent().before(content.replace(regexp, new_id));
}
I found that the link_to_add_fields helper won't work if the associated model is describe by a has_one. The has_one means the association does not get the klass object.
You can determine this is your problem by changing your relationship to has_many :object + s (your object name with an s) and passing your object in plural to link_to_add_fields.
You have done the same thing as this person here
Edit: (error on my part)
I am assuming you have an link_to_add_fields below this line
<%= link_to_remove_fields "Remove", f %>
as it seems that the _restaurant_fields.html.erb partial is incomplete. (no closing tag)
</p>
Remove the link_to_add_fields outside of the f.fields_for
That should solve the klass error.

Rails 3 Render / Partial

I'm very new to Rails 3 and I've followed some tutorials and now I'm trying to "play" with the code created. I have followed the tutorial from http://guides.rubyonrails.org/getting_started.html
I'm am trying to render the form for new posts on the homepage with this code:
<%= render :partial => "posts/form" %>
The posts/_form.html.erb looks like this:
<%= form_for(#post) do |f| %>
<% if #post.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#post.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% #post.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :title %><br />
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :content %><br />
<%= f.text_area :content %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
and this is the error I get:
undefined method `model_name' for NilClass:Class
Extracted source (around line #1):
1: <%= form_for(#post) do |f| %>
2: <% if #post.errors.any? %>
3: <div id="error_explanation">
4: <h2><%= pluralize(#post.errors.count, "error") %> prohibited this post from being saved:</h2>
Trace of template inclusion: app/views/home/index.html.erb
Rails.root: d:/server/cazare
Application Trace | Framework Trace | Full Trace
app/views/posts/_form.html.erb:1:in `_app_views_posts__form_html_erb___794893824_70478136_519766'
app/views/home/index.html.erb:5:in `_app_views_home_index_html_erb__967672939_70487520_0'
I understand that this may seem a piece of cake for some of you but I'm trying to understand how everything works on Rails so I hope you can understand me.
Thanks in advance !
#post variable is not instantiated in the Controller :)
so "#post = Post.new" inside the controller action should do the trick
Rails is attempting to build a form for the object #post. In order to do that, it needs to know what sort of object #post is; that way, it can find any existing data in the object and fill it into the form for you. Rails has a method grafted on to objects called model_name to do the lookup, but it won't be grafted onto NilClass (the class of the nil object).
I suspect that you haven't defined #post anywhere - it's an instance variable of the Controller, so you'd expect the controller to either find #post from the database, or to call #post = Post.new - so it's nil.
In the posts/_form.html.erb,
change
<%= form_for(#post) do |f| %>
to
<%= form_for(Post.new) do |f| %>

Resources