Ruby - Saving a Model shows a Get url in browser - ruby-on-rails

Ruby 2.2.4
Rails 4.2.6
PostgreSQL 9.5
I am trying to save a simple model, but when I submit the form, my browser url shows this "http://localhost:8080/notes/new?utf8=%E2%9C%93&authenticity_token=z0cyVNfUKYWDSDASDWFFZ96zj29UTtDYe8dLlKrI6Mbznb2SrTWNm%2BQ91D2s2AASD2345Fl3fTOneCC2dNg%3D%3D&note%5Btitulo%5D=ddddddd&note%5Bconteudo%5D=dddddddddddddddddd&commit=Create"
I am curious about this because other project, it has the same methods, same routes, the only difference is the model that only have one column, but it works fine.
def change
create_table :notes do |t|
t.text :titulo
t.text :conteudo
t.timestamps null: false
end
My controller: notes_controller.rb
def new
#note = Note.new
end
def create
#note = Note.new(note_params)
if #note.save
redirect_to '/'
else
render 'new'
end
end
private
def note_params
params.require(:note).permit(:titulo,:conteudo)
end
my form
<%= form_for(#note) do |f| %>
<div class="field">
<%= f.label :titulo %><br>
<%= f.text_area :titulo %>
<%= f.label :conteudo %><br>
<%= f.text_area :conteudo %>
</div>
<div class="actions">
<%= f.submit "Create" %>
</div>
<% end %>
my routes
Rails.application.routes.draw do
root 'notes#index'
get 'notes/new' => 'notes#new'
post 'notes' => 'notes#create'
I saw this post Rails form issuing GET request instead of POST request
but does not work for me.
Edit:
I fix it thanks to Anthony E, his answer made me look back to code and realize that I have a form inside a form. The outer form was in application.html.erb.
Thanks to all.

Rails can't infer the appropriate form route from your model. Try explicitly setting the form URL and submit method in your form_for:
form_for #note, url: "/notes", as: :note, html: { method: :post } do |f|
end
Alternatively, it may be simpler to use resourceful routing:
In routes.rb:
resources :notes, only: [:new, :create, :index]
This will create the following routes:
GET /notes/new # Maps to NotesController#new
POST /notes # Maps to NotesController#create
GET /notes # Maps to NotesController#index

Related

NoMethodError, undefined method `permits_path' for #<#<Class:0xbbb3ed0>:0xbbb34b0>

I'm new to ROR. I'm trying to create a page for parking permit application. I encountered this problem
I couldn't find the problem. Or maybe i missed something. Any help is appreciated.
This is my permit_controller.rb
class PermitController < ApplicationController
before_action :set_permit, only: [:show, :destroy]
def index
#permit = Permit.all
end
def new
#permit = Permit.new
end
def create
#permit = Permit.new(user_params)
if #permit.save
redirect_to root_path
else
flash[:success] = "Welcome to your profile!"
end
end
def destroy
end
def show
#permit = Permit.find(params[:id])
end
private
# Use callbacks to share common setup or constraints between actions.
def set_permit
#permit = Permit.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def permit_params
params.require(:permit).permit(:vehicle_type, :name, :studentid, :department, :carplate, :duration,:permitstart,:permitend)
end
end
This is my permit/new.html.erb
<% provide(:title, 'New Permit') %>
<h1>Permit Application</h1>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<%= form_for(#permit) do |f| %>
<%= render 'shared/error_messages' %>
<%= f.label :"Vehicle Type" %>
<%= f.text_field :vehicle_type, class: 'form-control' %>
<%= f.label :name %>
<%= f.text_field :name, class: 'form-control' %>
<%= f.label :"Student ID" %>
<%= f.text_field :studentid, class: 'form-control' %>
<%= f.label :department %>
<%= f.text_field :department, class: 'form-control' %>
<%= f.label :"Car Plate" %>
<%= f.text_field :carplate, class: 'form-control' %>
<%= f.submit "Confirm", class: "btn btn-primary" %>
<% end %>
</div>
</div>
This is my route.rb
Rails.application.routes.draw do
resources :users
resources :permit
get 'permit/destroy'
get 'permit/show'
root 'static_pages#home'
get 'homepage/index'
post 'permit' => 'permit#create'
get 'permitapplication' => 'permit#new'
get 'adminlogin' => 'admin_controller#index'
get 'contact'=> 'static_pages#contact'
get 'about' => 'static_pages#about'
get 'signup' => 'users#new'
get 'help' => 'static_pages#help'
post 'users' => 'users#create'
get 'login' => 'sessions#new' #Page for a new session
post 'login' => 'sessions#create' #Create a new session
delete 'logout'=>'sessions#destroy' #Delete a session
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
Instead resources :permit use resources :permits.
The biggest issue here is you don't have permit/new in your routes.rb file.
As has already been suggested, it might be better for you to leverage rails
with a resources call
in routes.rb
resources :permits
and remove lines
get 'permit/destroy'
get 'permit/show'
etc.
I'll attempt to consolidate our various answers and comments.
To solve your current problem, in config/routes.rb, change resources :permit to resources :permits. This exposes all seven RESTful routes for use in your application. (This also makes obsolete the custom permit routes, unless you're explicitly calling them from within their respective forms.) Information about RESTful routes/resources here: http://guides.rubyonrails.org/routing.html#crud-verbs-and-actions
Why is this valuable?
It's how your application knows to use controller actions in combination with views (and therefore forms). Say you have an edit action in your permits controller and app/views/permits/edit.html.erb has a form. Within this page's edit form, you need only have form_for #permit and Rails does all the rest. It knows you're using this particular route. I recommend you read about routing within Rails.
Please keep in mind Ruby on Rails has been carefully crafted to make things easy for you, the developer.

Cannot create new object in rails

I am trying to create a basic Item creation in rails but I am having trouble creating new item. I want to create item's name, say Wash the dishes. These are the codes that I have:
Routes:
resources :items
ItemsController:
class ItemsController < ApplicationController
...
def new
#item = Item.new
end
def create
#item = Item.new(item_params)
if #item.save
flash[:notice] = "Item was saved!"
redirect_to #item
else
flash.now[:alert] = "ERROR. ERROR."
render :new
end
end
...
private
def item_params
params.require(:item).permit(:name, :list_id)
end
end
items/new.html.erb
<%= form_for :item do |f| %>
<%= f.text_field :name %>
<%= f.submit %>
<% end %>
Lastly, schema:
create_table "items", force: :cascade do |t|
t.string "name"
t.integer "list_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
...
I got several different error codes, but this is the one I am currently stuck at (other times it showed different error code or it would simply prints out "ERROR. ERROR." (alert that I setup when save fails)
Routing Error
No route matches [POST] "/items/new"
When I go to rake routes:
POST /items(.:format) items#create
new_item GET /items/new(.:format) items#new
I followed suggestion from this SO post to check my routes and this is what I have:
2.2.2 :019 > r = Rails.application.routes
=> #<ActionDispatch::Routing::RouteSet:0x007fff323c3230>
2.2.2 :020 > r.recognize_path "/items/new"
=> {:controller=>"items", :action=>"new"}
I have also gone to rails c and I was able to create new item manually. (i = Item.new(name:"Test 123"); i.save)
What did I miss?
The problem is with your form. To understand what's wrong, do the following:
Start the rails server using rails s
Go to http://localhost:3000/items/new
Instead of filling in the form fields, view the source page
Check the form tag. Its submitting the form data to /items/new. ie.the action attribute is set to /items/new. Why is that?
From the documentation:
When the model is represented by a string or symbol, if the :url option is not specified, by default the form will be sent back to the current url (We will describe below an alternative resource-oriented usage of form_for in which the URL does not need to be specified explicitly).
<form action="/items/new" accept-charset="UTF-8" method="post">
In your routes.rb, there's no route matching POST /items/new
So, modify your form to
<%= form_for :item, url: items_path do |f| %>
<%= f.text_field :name %>
<%= f.submit %>
<% end %>
This generates a form tag which posts the data to /itemsrather than /items/new.
Or replace your form with
<%= form_for #item do |f| %>
<%= f.text_field :name %>
<%= f.submit %>
<% end %>
Now, the form will be submitted to /items. The advantage of using the second version is you can dry out your form for creating a new object and updating an existing object into a single view(partial).
For more, see http://guides.rubyonrails.org/form_helpers.html#binding-a-form-to-an-object
Try this in items/new.html.erb
<%= form_for #item do |f| %>
<%= f.text_field :name %>
<%= f.submit %>
<% end %>

No route matches [POST] "/tv_series/new"

When I display the form, I type in some stuff then I want it to take to the index view
_form.html.erb
<%= simple_form_for #series, :url => { :action => :new } do |f| %>
<%= f.input :title, label: "Series Title" %>
<%= f.input :description %>
<%= f.input :actor %>
<%= f.button :submit %>
<% end %>
Can some one please help me indentify the error for me? I don't know why its not creating the tvseries when I try to create, when I check tvseries.connection, it says its nil, there isn't anything in.
tv_series_controller.rb
class TvSeriesController < ApplicationController
def index
end
def new
#series = Series.new
end
def create
#series = Series.new(serie_params)
if #series.save
redirect_to root_path
else
render 'new'
end
end
private
def show
params.require(:series).permit(:title, :description,:actor)
end
end
new.html.erb
<h1>New Serie</h1>
<%= render 'form' %>
routes.rb
Rails.application.routes.draw do
resources :tv_series
root 'tv_series#index'
end
_create_series.rb
class CreateSeries < ActiveRecord::Migration
def change
create_table :series do |t|
t.string :title
t.text :description
t.string :actor
t.timestamps null: false
end
end
end
Remove the , :url => { :action => :new } and you should be good to go.
This is because there is no route that matches POST /tv_series/new. Instead let Rails figure out the route for you by removing the line above and it will use POST /tv_series.
If you run rake routes you should be able to see all of the available routes along w/ their corresponding HTTP verb (GET, POST, PATCH, etc)
On a sidenote I think your private method is named incorrectly. Looks like you have def show when what you meant to have is def serie_params.
Run rake routes to the console you will get different path for HTTP Verb (GET, POST, PUT/PATCH, DELETE)
Accordingly use the path.
In your case for creating tv_series you have to use post HTTP verb.
Replace :url => { :action => :new } with create action path provided for POST HTTP verb. It will work fine.
Refer this link: http://guides.rubyonrails.org/routing.html
For rails 4, as default it has same name of controller, model, and view. In this context, you have different name of model and controller/view. So you have to determine your URL in your form into this:
<%= simple_form_for #series, :url => { :controller => :tv_series, :action => :create }, :method => :post do |f| %>
or
<%= simple_form_for #series, :url => tv_series_path, :method => :post do |f| %>
I hope this help you.

No route matches [POST] "/articles/new"

When I try to submit the form its giving me the error
No route matches [POST] "/articles/new"
the files are: new.html.erb
this file which contains the form with a text field and text area:
<%= form_for :article, url: articles_path do |f| %>
here the url: is to match post request which is a create
form's title
<%= f.label :title %><br>
form's text field
<%= f.text_field :title %></p>
form's title
<%= f.label :text %><br>
form's text area
<%= f.text_area :text %></p>
<p>
<%= f.submit %>
</p>
<% end %>
route file is
Rails.application.routes.draw do
resources :article
end
controller is
the controller with its methods new and create
whenever I submit the form its giving the error, even I used the URL: articles_path which for default post request, I used #articles also in the form but it is giving me the same error. I am new to the Rails so I tried many ways but I could not find the solution
class ArticlesController < ApplicationController
def new #new method which is a get request
end
def create #create method which is a post request
end
end
whenever I submit the form its giving the error, even I used the url: articles_path which for default post request. and I kept
def create
end
in the controller
The reason why this occurs for many people using this tutorial is that they don't reload the form after changing the url option in the form_for helper.
Be sure to reload a fresh copy of the form before trying to submit it (you need the form to have the most recent form submission url).
change:
resources :article
to:
resources :articles #plural
that way it will map to:
articles_path POST /articles(.:format) articles#create
I changed app/views/articles/new.html.erb from:
<%= form_for :article do |f| %>
to:
<%= form_for :article, url: articles_path do |f| %>
You can find the answer on the official guideline.
Because this route goes to the very page that you're on right at the moment, and that route should only be used to display the form for a new article.
Edit the form_with line inside app/views/articles/new.html.erb to look like this:
<%= form_with scope: :article, url: articles_path, local: true do |form| %>
Your actions/methods in the controller do nothing. It should be something like:
class ArticlesController < ApplicationController
def new
#article = Article.new
end
def create
#article = Article.new(article_params)
if #article.save
redirect_to #article
else
render 'new'
end
end
private
def article_params
params.require(:article).permit()# here go you parameters for an article
end
end
In the view:
<%= form_for #article do |f| %>
RedZagogulins answer is right - that is the code you need to use in your articles controller
--
Routes
The clue to your problem is here:
No route matches [POST] "/articles/new"
Typically, when using the correct routing structure:
#config/routes.rb
resources :articles #-> needs to be controller name
You'll find that the new action is GET, not POST. This leads me to believe your system is set up incorrectly (it's trying to send the form data to articles/new, when it should just send to [POST] articles
If you follow the steps outlined by RedZagogulin, it should work for you
I was continually running into this problem and it came down to the fact that I had the following code in my navbar:
<%= link_to "Blog", controller: 'articles' %>
I switched to this and it all started working:
<%= link_to "Blog", articles_path %>
I'm still new to this so the different ways of doing things sometimes gets confusing.
In your case,
at first change the
#/config/routes.rb
resources :article
to
#/config/routes.rb
resources :articles #plural
# Changing this in Plural naming if your file name
# in #/app/view
# is plural
# (ex: /app/view/articles)
#
# and controller and it's class is also in plural naming
# (ex:
# in #/app/controllers/articles_controller.rb file
# class ArticlesController < ApplicationController
#
# end)
In some cases, we need to add a Post routes to make a Post Request of the form. Just add the lines in routes file:
#/config/routes.rb
Rails.application.routes.draw do
resources :articles #plural
post '/articles/new' => 'articles#create'
end
In order to get this working, I needed to combine instructions for two answers. First, I added a specific route in routes.rb to handle POST requests to '/articles/new':
Rails.application.routes.draw do
root "articles#index"
resources :articles
post '/articles/new' => 'articles#create'
end
And then I had to change the first line of the form to this <%= form_with model: #aricle do |form| %>:
<h1>New Article</h1>
<%= form_with model: #aricle do |form| %>
<p>
<%= form.label :title %><br>
<%= form.text_field :title %>
</p>
<p>
<%= form.label :body %><br>
<%= form.text_area :body %>
</p>
<p>
<%= form.submit %>
</p>
<% end %>

ActionController::RoutingError: No route matches [POST] "/locations/new"

Routes
resources :locations, :only => [:new, :create]
Controller
class LocationsController < ApplicationController
def new
#location = Location.new
end
def create
#location = Location.new(location_params)
if #location.save
flash[:notice] = 'Created location successfully'
redirect_to new_location_path
else
flash[:notice] = 'Invalid information. Please try again'
render :new
end
end
private
def location_params
params.require(:location).permit(:name, :street, :city, :state)
end
end
Error message when I click save.
ActionController::RoutingError:
No route matches [POST] "/locations/new"
view
<%= simple_form_for :locations do |form| %>
<%= form.input :name %>
<%= form.input :street %>
<%= form.input :city %>
<%= form.input :state %>
<%= form.submit 'Create location' %>
<% end %>
Using capybara to test that when I click on save it creates a new location. I'm not quite sure why it doesn't know what the post route is because I have the new and create routes. If I put a binding.pry right underneath the create method it doesn't get called. So my create method is not being called for some reason.
EDIT:
Rake Routes
locations POST /locations(.:format) locations#
new_location GET /locations/new(.:format) locations#new
A resource normally GETs to new and POSTs to create. So your form is probably submitting back to the new actions instead of submitting to the create action.
Here's the guide for this: http://guides.rubyonrails.org/routing.html#crud-verbs-and-actions
The problem was in the views.
<%= simple_form_for :locations do |form| %>
<%= form.input :name %>
<%= form.input :street %>
<%= form.input :city %>
<%= form.input :state %>
<%= form.submit 'Create location' %>
<% end %>
I was calling on locations symbol when I should have been calling on the instance variable #location from the controller.
The actual problem was that rails 3.2.12 doesn't take private params
Using resources, the new action should be fetched with GET instead of POST. create will be POST. Check your rake routes

Resources