Good Day, i'm having a trouble with the routes in Ruby on Rails 4
Error:
undefined method `routes_path'
View:
<h1>Load data</h1>
<div class="row">
<div class="span6 offset3">
`<%= form_for #route, :html => { :multipart => true } do %>
<%= hidden_field_tag 'current_user', #current_user %>
<%= file_field_tag :file %>
<%= submit_tag "Import", style: 'margin-top: -10px', class: "btn btn-primary" %>
<% end %>
Controller:
def new
#route = current_user.build_route
end
def create
nil_flag = Route.import(params[:file], current_user)
if nil_flag == 1
flash[:success] = "Data created."
redirect_to route_path(current_user)
else
flash[:error] = "Error"
redirect_to load_data_path
end
end
Model:
def self.import(file, current_user)
#user = current_user
#route = #user.build_route
#nil_flag = 0
File.open(file.path, 'r') do |f|
.
.
.
#etc
end
Routes
match '/load_data', to: 'routes#new', via: 'get'
Views, controller and model are named "Route"
Is a problem with the route in the view or something else? Thank you
Just as a first impression, without looking into it in detail - you may have trouble using routes as a class name, it's already a class name under ActionDispatch.
However, I think your problem is actually your route:
match '/load_data', to: 'routes#new', via: 'get'
This isn't a resource route, it won't generate the kind of functionality that allows you to use the form tag syntax <%= form_for #route...
Either define routes as a resource:
resources :routes
Or define a url in your form:
<%= form_for #route, :url => some_url, :html => { :multipart => true } do %>
Matt (the previous answer author) pretty much answered the question, just want to notice that you can also append the as option to your route to give it a name:
match '/load_data', to: 'routes#new', via: 'get', as: 'routes'
this will "define" the routes_path for you.
Related
I'm trying to add edit functionality to my web app, and am having some trouble. The error page I get back when I try to complete an edit of my Request object indicates that it couldn't find the right route, but the same error page contains a list of routes which includes the route it's looking for. So I'm a bit flummoxed.
The "new" method is almost identical to this edit method and the pages are almost identical as well.
The error page begins No route matches [POST] "/requests/19/edit" and then, partway down the route listing, I see this:
requests_path GET /requests(.:format) requests#index
POST /requests(.:format) requests#create
new_request_path GET /requests/new(.:format) requests#new
edit_request_path GET /requests/:id/edit(.:format) requests#edit
request_path GET /requests/:id(.:format) requests#show
PATCH /requests/:id(.:format) requests#update
PUT /requests/:id(.:format) requests#update
DELETE /requests/:id(.:format) requests#destroy
So Rails seems to be generating a request_path which expects a PATCH, not a POST, right?
routes.rb
Rails.application.routes.draw do
root "pages#index"
resources :destinations
resources :users
resources :manifests
resources :requests
:
request.rb
class Request < ActiveRecord::Base
validates_presence_of :justification
validates_presence_of :required_by
belongs_to :user
belongs_to :manifest
belongs_to :network
has_many :uploaded_files
scope :sorted, lambda{ order("required_by") }
end
edit.html.rb
<% #page_title = "Update Request" %>
<%= link_to("<< Back to List", {:action => 'index'}, :class => 'back-link') %>
<div class="requests edit">
<h2>Update Request</h2>
<%= form_for :request, url: request_path(#request) do |f| %>
<%= render(:partial => "form", :locals => {:f => f}) %>
<div class="form-buttons">
<%= submit_tag("Update Request") %>
</div>
<% end %>
</div>
requests_controller.rb
def update
#request = Request.find(params[:id])
p = {'file' => params[:request][:uploaded_file], 'request_id' => #request.id}
uf = UploadedFile.create(p)
if #request.update_attributes(request_params)
flash[:notice] = "Request updatred succesfully"
redirect_to :action => 'show', :id => #request.id
else
render 'edit'
end
end
What have I missed?
Change
<%= form_for :request, url: request_path(#request) do |f| %>
to
<%= form_for :request, url: request_path(#request), method: :patch do |f| %>
in your edit.html.erb
form_for(as you are using it) sets POST as default HTTP verb. You need to alter it by setting method :patch which responds to the update action.
You can simplify it to just
<%= form_for #request do |f| %>
Check the APIdoc for more Info.
Can I disable auto redirect in ruby on rails, here my example: In my controllers
class WelcomeController < ApplicationController
def index
#a = params[:link]
if #a != nil
Kernel.system("ls")
redirect_to root_path
else
end
end
end
I don't want to redirect to root_path and stay in current pages, so I remove redirect_to root_path, like this:
def index
#a = "abcd"
if #a != nil
Kernel.system("ls")
else
end
end
But my app still auto redirect to root_path, I don't know how to fix that, please! help me:)
my routes:
root 'welcome#index'
match '/upload', to: 'welcome#index', via: 'post'
my html:
<%= form_tag(upload_path, :id => "form_check") do %>
<%= text_field_tag :link %>
<%= submit_tag("Process")%>
<%end%>
I think your problem isn't really auto redirect. You are "redirected" to your index because this line doesn't match: match '/upload', to: 'welcome#index', via: 'post'.
What you should do is to separate index and upload. It will be far easier to manage.
routes:
root 'welcome#index'
get 'form' => 'welcome#form', as: :form_path
post 'upload' => 'welcome#upload', as: :upload_path
form page:
<%= form_tag(upload_path, :id => "form_check") do %>
<%= text_field_tag :link %>
<%= submit_tag("Process")%>
<%end%>
And then you can create your new actions inside welcome, called form and upload. The last one redirect you to /form, so you can see your form again.
Hello i'm new one in ruby on rails. I have strange problem. I use some tutorial and get error which i shouldn't get.
I have controller
class DiaryController < ApplicationController
before_action :authenticate_user!
respond_to :html, :xml, :json
respond_to :js, :only => [:create, :update, :destroy]
def create
#record = Record.create(record_params)
#record.userId=current_user.id
if request.xhr? || remotipart_submitted?
sleep 1 if params[:pause]
render :layout => false, :template => (params[:template] == 'escape' ? 'comments/escape_test' : 'diary/create'), :status => (#record.errors.any? ? :unprocessable_entity : :ok)
else
redirect_to diary_path
end
end
def add
#record = Record.new
#respond_with(#record, :layout => false)
respond_with do |format|
format.html { render :layout => ! request.xhr? }
end
end
# PUT /comments/1
# PUT /comments/1.xml
def update
#record = Record.find(params[:id])
respond_with do |format|
format.html{ redirect_to #record }
end
end
def delete
#comment = Comment.destroy(params[:id])
end
def edit
#record = Record.find(params[:id])
end
def index
#records = Record.where(userId: current_user.id)
end
private
def record_params
params.require(:record).permit(:photo, :comment, :date, :photo_cache)
end
end
Have view
<h1 align="centre">
Добавить запись
</h1>
<%= render 'form' %>
<%= link_to 'Отмена', diary_path, :id => 'cancel-button' %>
and
<%= form_for(#record, :remote => (params[:action] == 'add' ? true : false)) do |f| %>
<fieldset>
<div class="field">
<%= f.label :date, :class => 'required' %><br />
<%= f.date_select :date %>
</div>
<div class="field">
<%= f.label :comment %><br />
<%= f.text_area :comment %>
</div>
<div class="field">
<%= image_tag(#record.photo_url(:thumb)) if #record.photo? %><br />
<%= f.label :photo %><br/>
<%= f.file_field :photo %><br/>
<%= f.hidden_field :photo_cache %>
</div>
</fieldset>
<table>
<tr>
<td>
<div class="actions">
<%= f.submit "Добавить", :data => {:'disable-with' => "Submitting..."} %>
</div>
</td>
<td>
<%= link_to 'Отмена', diary_path, :id => 'cancel-button' %>
</td>
</tr>
</table>
And get ActionView::Template::Error (undefined method `records_path' for #<#:0x000000054461c8>): error on "<%= form_for(#record, :remote => (params[:action] == 'add' ? true : false)) do |f| %>" line. Even records_path i did'n use.
I Have routes
devise_for :users
get 'welcome/index'
root 'welcome#index'
get 'diary' => 'diary#index'
get 'diary/add_record', to: 'diary#add', as: 'add_record'
post 'diary/add_record', to: 'diary#create'
get 'diary/edit_record/:id', to: 'diary#edit'
delete 'diary/edit_record/:id' => 'diary#delete
And and try to use add_record route. Maybe it would be better to use resources :records.But i want to figure out why my routes doesn't work.
view name "diary".
Because you're new to RoR, let me explain why you're receiving the error
form_for
form_for is the likely reason why you're receiving this error (oh, I just saw it actually states this is where the error occurs - sweet)
The problem you have is that form_for is meant as a way to render a form around an ActiveRecord object. It's mean to give some semi-persistence to the data, by using AR in both the new and create actions (allowing you to show the in-putted data on the form after submission)
When you pass an object to form_for, Rails automatically "builds" the form from the ActiveRecord object, one of the options it uses being the url
--
Routes
The problem you have is the object you pass to the form_for takes the model_name attribute to build the route. This means if you want to use the form_for method by just passing an object, it's going to look for routes pertaining directly to that object
If you don't have any [model]_path route set up, you'll likely receive the error you're getting. The fix firstly involves the routes, and secondly involves the controller:
#config/routes.rb
root 'welcome#index'
devise_for :users
resources :diary, path_names: { new: "add_record", create: "add_record", edit: "edit_record", destroy: "edit_record" }
resources :welcome, only: :index
This is down to the idea that Rails' routing structure is built around resources - every route you have should lead to a specific controller action. Whilst including custom actions is completely fine, you have to appreciate that the basis of the routing structure is to construct resourceful routing, which essentially means that Rails perceives every controller / model to have corresponding routes:
--
URL
The second thing to observe is the url of the form
If you have your routes set up as above, and if your routing structure differs from your model structure (different names), you'll want to use the following setup to define the url explicitly:
<%= form_for #record, url: your_custom_path do |f| %>
I'm having a trouble with the routes in Ruby on Rails 4, and receiving this error:
undefined method `routes_path'
My view is:
<h1>Load data</h1>
<div class="row">
<div class="span6 offset3">
<%= form_for #route, :html => { :multipart => true } do %>
<%= hidden_field_tag 'current_user', #current_user %>
<%= file_field_tag :file %>
<%= submit_tag "Import", style: 'margin-top: -10px', class: "btn btn-primary" %>
<% end %>
</div>
</div>
My controller is:
def new
#route = current_user.build_route
end
def create
nil_flag = Route.import(params[:file], current_user)
if nil_flag == 1
flash[:success] = "Data created."
redirect_to route_path(current_user)
else
flash[:error] = "Error"
redirect_to load_data_path
end
end
My model is:
def self.import(file, current_user)
#user = current_user
#route = #user.build_route
#nil_flag = 0
File.open(file.path, 'r') do |f|
.
.
.
#etc
end
The routes are:
match '/load_data', to: 'routes#new', via: 'get'
My views, controller and model are named "Route".
Is there a problem with the route in the view or something else?
You have to specify a name for your route so Rails will create the _path helper:
match '/load_data', to: 'routes#new', via: 'get', as: :routes
This creates a routes_path helper that returns /load_data.
It's usually easier to use resource routing:
resources :routes, path: '/load_data'
The above line will create the following routes:
HTTP Verb Path Action Named Helper
GET /load_data index routes_path
GET /load_data/new new new_routes_path
POST /load_data create routes_path
GET /load_data/:id show route_path(:id)
GET /load_data/:id/edit edit edit_route_path(:id)
PATCH/PUT /load_data/:id update route_path(:id)
DELETE /load_data/:id destroy route_path(:id)
You can run rake routes in your terminal to get a list of the available routes.
Having a bit of trouble with the following ruby on rails code snippet - I have books and would like to update a book's name, here is how I try to do it:
<h1>Edit the book "<%= #book.name %>"</h1>
<%= form_tag action: :update, id: #book do %>
<p>
<label for="book_name">Name</label>
<%= text_field :book, :name %>
<%= submit_tag 'Save changes' %>
</p>
<% end %>
This is what I do in the books controller:
def edit
#book = Book.find(params[:id])
end
def update
#book = Book.find(params[:id])
if #book.update_attributes(params[:book])
redirect_to :action => 'show', id => #book
else
#subjects = Subject.find(:all)
render :action => 'edit'
end
end
These are my routes:
root to: 'authors#index'
resources :books, :authors
When I click the submit button in the form, it gives me No route matches [POST] "/books/5" and directs to localhost:3000/books/5 instead of staying and localhost:3000/books/5/edit
What am I doing wrong here? Shouldn't there be a put method for updating stuff somewhere rather than a post method?
Updates should use put not post.
<%= form_tag( { :controller => :books, :action => :update, :id => #book.id }, { :method => :put } ) do %>
or better yet use form_for
<%= form_for #book do |f| %>
On your console run "rake routes" and it will print out all available routes.
Please try this:
We need to specify match in routes file.
match "/books/:id" => "books#update"
resources :books should do the job. you dont have to explicitly use "match".
def edit
#book = Book.find(params[:id])
end
form.html
form_for #book, :method => :put do |f|
def update
#book = Book.find(params[:id])
#book.update_attributes(params[:book])
end
this should do the job.
I had this issue before. Everything was right but still getting the error then I found out it was
gem 'rails-api'
Removed it and it all worked fine.