I decided to start a Ruby on Rails project without scaffolding because I actually wanted to learn in the process. I have searched this site but cannot seem to find the answer to my question so I will ask here. I started a Rails project where the user enters their grades. Unfortunately, on the new grade page when the user hits Create Grade I get the error in the subject line. Here is my code for the form that I use in the new page under the grade controller.
<%= form_with(model: grade, local: true) do |f| %>
<% if grade.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(grade.errors.count, "error") %> prohibited this grade
from being saved:</h2>
<ul>
<% grade.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :assignment %>
<%= f.text_field :assignment %>
</div>
<div class="field">
<%= f.label :score %>
<%= f.text_field :score %>
<div class="actions">
<%= f.submit %>
</div>
This is my routes page:
Rails.application.routes.draw do
resources :grades
root 'grade#index'
get 'grade/index'
get 'grade/show'
get 'grade/new'
get 'grade/edit'
get 'grade/create'
get 'grade/update'
get 'grade/destroy'
# For details on the DSL available within this file, see
http://guides.rubyonrails.org/routing.html
end
If more code is needed to answer the question please let me know.
Based on the title of your question, Rails is looking for a file called app/controllers/grades_controller.rb file that defines the GradesController class.
Create the following file, and you should get to the next step
# app/controllers/grades_controller.rb
class GradesController < ApplicationController
def new
#grade = Grade.new
end
def create
# logic for persisting the grade object goes here
end
# other controller methods, here
end
In the form for a new grade, use the instance variable (the one with the # symbol) you defined in the GradesController#new method:
<%= form_with(model: #grade, local: true) do |f| %>
In your routes, this is all you should need:
Rails.application.routes.draw do
resources :grades
root 'grades#index' # not 'grade#index'
end
Controllers are plural, check the name of the controller file to ensure it's plural then check the controller class name change both from GradeController to GradesController.
Related
I'm new to RoR. Wanted to try if my next web app should be RoR based. Started out following this trail: https://guides.rubyonrails.org/getting_started.html. Worked like a charm in the beginning, but i'm unable to get the darn thing to create new records. Any hint as to what i'm missing is appreciated.
The error i'm getting is this:
D, [2020-12-18T09:59:56.917197 #132399] DEBUG -- : Createevent
F, [2020-12-18T09:59:56.917893 #132399] FATAL -- :
ActionController::ParameterMissing (param is missing or the value is empty: Event):
app/controllers/event_controller.rb:33:in `event_params'
My routing looks like this:
Rails.application.routes.draw do
post 'event/new', to: 'event#create'
resources :event
end
(I'm baffled by the need for specifying the POST above, but without it the create is never fired. ).
The eventcontroller looks like this:
class EventController < ApplicationController
def index
#events = Event.all
end
def show
#event = Event.find(params[:id])
end
def new
logger = Rails.logger
logger.info 'NewEvent'
#event = Event.new
end
def create
logger = Rails.logger
logger.debug 'Createevent'
#event = Event.new(event_params)
logger.debug 'Eventcreated'
if #event.save
redirect_to event_path
else
render :new
end
end
private
def event_params
params.require(:Event).permit(:EventName, :Description, :EventStart, :EventEnd, :Maxparticipants, :Waitlist )
end
end
Index and show works fine.
The new.html.erb looks like this:
<h1>New Event</h1>
dsfsdfds
<%= form_with model: #Event do |form| %>
<div>
<%= form.label :eventname %><br>
<%= form.text_field :EventName %>
<%= #event.errors.full_messages_for(:EventName).each do |message| %>
<div><%= message %></div>
<% end %>
</div>
<div>
<%= form.label :Description %><br>
<%= form.text_field :Description %>
<%= #event.errors.full_messages_for(:description).each do |message| %>
<div><%= message %></div>
<% end %>
</div>
<div>
<%= form.label :EventStart %><br>
<%= form.text_field :EventStart %>
<%= #event.errors.full_messages_for(:eventstart).each do |message| %>
<div><%= message %></div>
<% end %>
</div>
<div>
<%= form.label :Eventend %><br>
<%= form.text_field :Eventend %>
<%= #event.errors.full_messages_for(:eventend).each do |message| %>
<div><%= message %></div>
<% end %>
</div>
<div>
<%= form.label :Maxparticipants %><br>
<%= form.text_field :Maxparticipants %>
<%= #event.errors.full_messages_for(:Maxparticipants).each do |message| %>
<div><%= message %></div>
<% end %>
</div>
<div>
<%= form.label :Waitlist %><br>
<%= form.text_field :Waitlist %>
<%= #event.errors.full_messages_for(:waitlist).each do |message| %>
<div><%= message %></div>
<% end %>
</div>
<div>
<%= form.submit %>
</div>
<%= submit_tag "Create" %>
<% end %>
Routes:
Prefix Verb URI Pattern Controller#Action
event_new POST /event/new(.:format) event#create
event_index GET /event(.:format) event#index
POST /event(.:format) event#create
new_event GET /event/new(.:format) event#new
edit_event GET /event/:id/edit(.:format) event#edit
event GET /event/:id(.:format) event#show
PATCH /event/:id(.:format) event#update
PUT /event/:id(.:format) event#update
DELETE /event/:id(.:format) event#destroy
Things created using:
bin/rails generate model Event EventName:string Description:string EventStart:datetime EventEnd:datetime Maxparticipants:integer WaitList:integer
bin/rails generate controller Event index
Version:
About your application's environment
Rails version 6.0.3.4
Ruby version ruby 2.7.2p137 (2020-10-01 revision 5445e04352) [x86_64-linux]
RubyGems version 3.1.4
Rack version 2.2.3
Thanks to Hackman & nathanvda for clarifying. I scratched everything and started over and i finally got it working. Still way too much woodo and black magic for my taste though. The error message part got me baffled for three consecutive hours.
As stated i followed the guide and therefore ended up using (in new)
<%= form_with model: #event do |form| %>
<% if #event.errors.any? %>
<h2>Errors</h2>
<ul>
<% #event.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
<% end %>
...
Which works (well, sort of). The record gets saved if ok, the validations rules gets fired
class Event < ApplicationRecord
validates :eventname, presence: true
validates :description, presence: true, length: { minimum: 20 }
end
and if violated no record gets written to the database, but no error messages either. Nil. Nothing. After poking around on the internet i ended up changing to
<%= form_for #event do |form| %>
and then error reporting works. Only problem with this solution is that the use of form_for is discouraged as it is being rendered obsolete.
Final version ended up being:
<%= form_with model: #event, local: true do |form| %>
Which does the trick.
Next step in my evaluation will be the use of natural keys as the use of surrogate keys is not an option for some of the data structures needed in this project. (during my poking around i got the impression that natural keys are some kind of a sore tooth in RoR, but time will show.
To start out, your resources in the routes should be pluralized. So resources :event should be resources :events
Also the controller name should be pluralized. So EventController would become EventsController.
Now the needed routes should work fine and you can get rid of the specified POST in your routes.rb
Now inside your controller you have the event_params method. There it is preferred to downcase/snake_case the names like this:
def event_params
params.require(:event).permit(:event_name #etc)
end
If your column names in DB are EventName etc, I would advice to rename them.
Last thing: In your form you got #Event with uppercase while in the controller#new action you defined #event with lowercase. Use lowercase everywhere.
So if you had started as follows:
bin/rails generate model Event event_name:string description:string event\-start:datetime event_end:datetime max_participants:integer wait_list:integer
bin/rails generate controller events index
Then the generated code would work a lot better.
A few tips to clarify:
in ruby we only write classes with a capital, for variables we use snake case (everything lowercase and words connected with underscores). So by extension when generating a model all attributes should be snake cased
a controller in general uses the plural form, since it "controls" all the events (not just one).
I'm new to rails and trying to create a new page with a form, fairly simple, but it keeps coming back with this error (listed below) on the <%= form_for #whiteboard do |f| %>line. I've looked at similar posts where people are having the same issue as me but none of the solutions seem to work for me. Would greatly appreciate some help, thanks!
Error Message:
NoMethodError in Whiteboard#new
undefined method `whiteboards_path' for #<#<Class:0x37014d8>:0x36b2d10>
Did you mean? whiteboard_path
<%= form_for #whiteboard do |f| %>
<div>
<% f.label :title %>
<% f.text_field :title %>
</div>
My Controller:
class WhiteboardController < ApplicationController
def index
#whiteboards = Whiteboard.all;
end
def show
#whiteboard = Whiteboard.find(params[:id])
end
def new
#whiteboard = Whiteboard.new
end
end
My View (whiteboard/new.html.erb):
<%= form_for #whiteboard do |f| %>
<div>
<% f.label :title %>
<% f.text_field :title %>
</div>
<div>
<% f.label :description %>
<% f.text_field :description %>
</div>
<div>
<% f.submit :title %>
</div>
<% end %>
My routes:
Rails.application.routes.draw do
root to: 'home#index'
resources :whiteboard
get 'whiteboard/wbpage'
get 'home/index'
get 'home/info'
devise_for :users
end
This is a simple pluralization error.
resources :whiteboards
In Rails resources should always be plural. On the rare occasion that you have a real singular resource you should use resource instead.
My Suggestion please mind it
when you create controller use pluralization
when you create Model use Singular (first letter must be camel case)
For Example
rails g controller articles
rails g model Article
I created a sample webpage in rubyonrails which has two textbox and a button . When i enter some data in the text box and click the button no error appears . But the data is not stored in the data base . What is the mistake that i committed .
login.html.erb file :
<%= form_for #product, url:{action: "login"} do |f| %>
<% if #product.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#product.errors.count, "error") %> prohibited this product from being saved:</h2>
<ul>
<% #product.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :username %><br>
<%= f.text_field :username %>
</div>
<div class="field">
<%= f.label :password %><br>
<%= f.text_field :password %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
routes.rb file:
Sample::Application.routes.draw do
get "sample/login"
root 'sample#login'
post 'sample/:id' => 'sample#login'
end
sample controller file :
class SampleController < ApplicationController
def login
#product=Logz.new
end
end
and the model class name Logz contains the necessary field names
username and password . If there was any error i could manage . but it shows no errors.
I had the same problem once. I dont know how its happened . but i just changed the content in database.yml
localhost:yourdb_development
into
127.0.0.1:ypurdb_development
and i got it working.
You are sending the data to method login, but it just instantiate a new Product and it aren't receiving any attributes... and even if received... it are not saving the Product at all, so does not persist the data.
Try add a method create... that will be responsible for receive the data and save
class SampleController < ApplicationController
def create
#product = Logz.new(params[:product])
if #product.save
format.html { redirect_to 'sample#login', notice: 'Data saved successfully' }
else
flash[:notice] = 'A wild error appeared'
end
end
After that, create the route to post 'sample/create' and change the action to where your form send the data... form_for #product, action: "create", method: 'post'
Doing that... i will be possible to persist the data on your database...
PS:
You can use the content of that method inside your login method... but I dont recommend that... it is ugly and does not follos the conventions of rails.
I even recommend you to do a refactory... because it doesn't make sense access a SampleController in order to create a Product... that is persisted in an object called Logz...
The best practice is all follow the same name... LogzController, #logz, and finally your model Logz. and preferably your routes following the same pattern...
Another thing is, it would be nice to change your method login to a method call 'new' because that method you use to fill a new Logz... not to login...
My simple form is not doing a POST. I've been looking at this and haven't been able to see what is wrong (I'm sure it's in my routes). Here's what I have:
view:
views/buyers/new.html.erb
<%= form_for(#buyer) do |f| %>
<%= f.text_field :phone %><br />
<%= f.text_field :make %><br />
<%= f.text_field :model %><br />
<%= f.submit %>
<% end %>
controller:
BuyersController
def new
#title = "Welcome to Car Finder"
#buyer = Buyer.new
end
def create
#buyer = Buyer.new(params[:buyer])
if #buyer.save!
redirect_to success
else
redirect_to :back
end
end
routes:
resources :buyers
rake routes:
buyers GET /buyers(.:format) buyers#index
POST /buyers(.:format) buyers#create
new_buyer GET /buyers/new(.:format) buyers#new
edit_buyer GET /buyers/:id/edit(.:format) buyers#edit
buyer GET /buyers/:id(.:format) buyers#show
PUT /buyers/:id(.:format) buyers#update
DELETE /buyers/:id(.:format) buyers#destroy
When I submit the form, it stays on the same page, never going to the create action. Below is from the log
Started GET "/?..[params]..."
Processing by BuyersController#new as HTML
Thanks for any help you can give
It is probably wise to restart your server. You're issue may lie in validations you have at your persistence level or in your buyer.rb file. Add this to the _form.html.erb:
<% if #buyer.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#buyer.errors.count, "error") %> prohibited this from being saved: </h2>
<ul>
<% #buyer.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
Try to complete the request again. See if any errors are being thrown. Fix those.
I'm facing this error for quite some time now, I've tried a lot of solutions but none is working. Making my scenario clear :
1) I'm not using scaffold command & creating the whole thing manually
2) The error is generated on trying to create a new Charity
ERROR:
Showing /home/hitesh/Rails/ReachOut/app/views/charity/_form.html.erb where line #1 raised:
undefined method `charities_path' for #<#<Class:0x000000035ab3f8>:0x0000000344f220>
Extracted source (around line #1):
1: <%= form_for(#charity) do |f| %>
2: <% if #charity.errors.any? %>
3: <div id="error_explanation">
4: <h2><%= pluralize(#charity.errors.count, "error") %> THis is where i screwed prohibited this charity from being saved:</h2>
MY _form.html.erb LOOKS LIKE THIS :
<%= form_for(#charity) do |f| %>
<% if #charity.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#charity.errors.count, "error") %> THis is where i screwed prohibited this charity from being saved:</h2>
<ul>
<% #charity.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>
MY routes.rb contains the entry for a charity
ReachOut::Application.routes.draw do
resources :charity
# The priority is based upon order of creation:
# first created -> highest priority.
My CharityController :
class CharityController < ApplicationController
# GET /charity/new
# GET /charity/new.json
def new
#charity = Charity.new
respond_to do |format|
format.html #new.html.erb
format.json { render json: #charity}
end
end
and My charity.rb (MODEL) : does contain a charity class
...
Guys I;ve tried a lot of things (changing # => :) but still m not able to remove this error ... Hope anyone of you can help me in it... I searched for charities_path in my whole system and could find nothing :) :(.
you need resources :charities in routes.rb
And controller must be named as CharitiesController
Or you must manually set path helper method, but in this case you can face another problems, better follow rails naming rules