Rails - Destroy action asking for 'GET' - ruby-on-rails-5

I am trying to create a website that a user can signup, login, and logout. I have successfully written down the signup and login part. Actually, my 'logout' link was also working yesterday. Somehow, now I am getting this error whenever I try to logout:
No route matches [GET] "/en/logout"
I have my 'en' locale and it's working without a problem with other paths. It's somehow asking for a [GET] route for logout and I couldn't find where I did a mistake.
session_controller:
def destroy
session.delete(:user_id)
redirect_to root_path
end
All routes that I have wrote for session controller:
get 'login', to:'session#new'
post 'login', to:'session#create'
delete 'logout', to: 'session#destroy'
HTML:
<ul class="navbar-nav justify-content-end">
<%= render(partial:'active_nav_item', locals:{ border: true, title: translate('profile'), uri: profile_path }) %>
<%= link_to translate('logout'), logout_path, method: :delete, class: 'nav-link' %>
</ul>
Routes for session controller:
login_path GET /:locale/login(.:format) session#new
POST /:locale/login(.:format) session#create
logout_path DELETE /:locale/logout(.:format) session#destroy

Related

Rails - redirect to don't save history

I'm using Devise for my app, and I customize the session controller to handle sign-in by otp code, my controller:
class SessionsController < Devise::SessionsController
def new
end
def create
mobile_number = User.set_number(params[:mobile_number], params[:country_code])
#user = User.active.fetch_user(nil, mobile_number)
if #user
otp = Sms.send_sms(mobile_number)
if otp == false
flash[:alert] = 'OTP Sending failed'
else
#user.otp = otp
#user.otp_generated_at = Time.zone.now
redirect_to sessions_otp_form_path(id: #user.id) if #user.save
end
else
flash[:alert] = 'User not found'
end
end
end
The routes:
devise_for :users,
path: '',
path_names: { sign_in: 'login', sign_out: 'logout', registration: 'signup', sign_up: '' },
controllers: { sessions: 'sessions', registrations: 'registrations', passwords: 'passwords'}
devise_scope :user do
post '/send_otp', to:'sessions#send_otp'
get 'sessions/otp_form'
My view:
<div class="login_form">
<%= form_with model:#user, url:user_session_path do |f| %>
...
</div>
From the home page, I click to login button to go to /login page, if I input the correct number, I will be redirected to otp form(sessions/otp_form) where I can use the otp code to sign in. And the issue occurs here, when I am in otp form, I want to back to the previous page(the login page where I type my phone number) by clicking back on the browser, but the browser instead of steps back to the previous URL(/login in this case) it steps back two steps to go to home page.
I checked on browsers(both firefox and chrome), the login path didn't be stored.
To ensure the issue not coming from redirect_to, I create a simple form then submit -> redirect -> back in this case I can back to the previous URL step by step. I also created a simple app that using Devise without any customization, and it works well(doesn't lose the previous path). Currently, I'm not sure what is happening to my code. Any advice and suggestions will be greatly appreciated.
I found the reason. It is not related to the back end. It due to my form:
<div class="login_form">
<%= form_with model:#user, url:user_session_path do |f| %>
...
</div>
By default form_with attaches the data-remote attribute to the form. As a consequence, the form will be submitted using Ajax. That's why this history lost. So, to fix my issue, I disabled the default feature by adding: local: true option to the form. And it works.
<div class="login_form">
<%= form_with model:#user, url:user_session_path, local: true do |f| %>
...
</div>

Rails App on Ubuntu running Apache and Passenger throws 404 with params

I am trying to set up a server to host my rails apps. I have one I am testing and it is giving me a 404 error when I call a controller action while passing params in the URL. I have this app deployed on Heroku and it runs perfectly. Any action that is called without params work perfectly on the new server. It is only the action that passes the params that is giving me the 404.
Also I ran it locally with Webrick on the server and it works fine. It only has this issue when running on passenger.
Any ideas what might cause this or where I should start to find the issue?
This is the request being sent
Request GET /groups/2/set_and_redirect/%2Fgroups%2F2%2Fgroups_lists HTTP/1.1
This is the body of the 404 response
The requested URL /groups/2/set_and_redirect//groups/2/groups_lists was not found on this server.
Edit
This is the partial that is causing the issue. Specificaly the link_to group.name. The edit and delete both work fine and the set and redirect works fine on Heroku and Webrick.
<% #groups.each do |group| %>
<h4><div>
<%= link_to group.name, groups_set_and_redirect_path(:id => group.id, :path => group_list_path(id: group.id) ), remote: true %>
<%= link_to ('<i class="glyphicon glyphicon-edit"></i>').html_safe, edit_group_path(group),'data-toggle' => 'modal', 'data-target' => "#group-modal#{group.id}", remote: true %>
<%= link_to ('<i class="glyphicon glyphicon-trash text-danger"></i>').html_safe, group, method: :delete, data: { confirm: 'Are you sure?' }, remote: true %>
</div></h4>
<%end%>
<div> <%= link_to ('<i class="glyphicon glyphicon-plus text-success"></i>').html_safe, "#group-modal", 'data-toggle' => 'modal', class: 'btn btn-lg' %> </div>
I changed my route from
get 'groups/:id/set_and_redirect/:path' => 'groups#set_and_redirect',
:as => :groups_set_and_redirect
to
get 'groups/:id/set_and_redirect' => 'groups#set_and_redirect', :as =>
:groups_set_and_redirect
and now it works
Adjust your routes.rb so that a double slash doesn't occur (perhaps by using a named parameter for path).

Rails 3 - Invoke controller method with submit_tag

I'm very new to rails, so please excuse me if I'm asking such a basic question.
I had this form on my html.erb page:
<%= form_tag(posts_path(:controller => "posts", :action => "create_thread"), :method => "post") do%>
Title:
<br></br>
<%= text_area_tag 'title', 'Thread\'s title is required!', :rows => 1, :cols => 30 %>
<br></br>
Message:
<br></br>
<%= text_area_tag 'body', nil, :rows => 15, :cols => 50 %>
<br></br>
<%= submit_tag "Create Thread" %>
<% end %>
I defined the "create_thread" method in the controller:
class PostsController < ApplicationController
def create_thread
logger.info("Thread created: ")
end
end
In the routes.rb file, I created a route for the submit:
resources :posts do
collection do
post 'index', :as => :create_thread
end
Basically, when I click on the "Create Thread" button on the form, I would like rails to execute the function "create_thread" in the PostsController class, and then load the "index" page.
However, when I clicked on the "Create Thread" button, it took me straight to the "index" page (so the path is working, at least), but it did not execute the "create_thread" function in the controller.
This was what it showed on the console when I clicked on the button:
Started POST "/posts?action=create_thread" for 127.0.0.1 at 2013-07-14 22:08:35 -0700
Processing by PostsController#index as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"9XVUrStaysmdOc6ug/A3XXX/8bzLkY8ixCkiAfHs9fU=", "title"=>"Thread's title is required!", "body"=>"", "commit"=>"Create Thread"}
Here's the output of rake routes
root / posts#index
new_thread_posts GET /posts/new_thread(.:format) posts#new_thread
create_thread_posts POST /posts(.:format) posts#index
current_thread_post GET /posts/:id/current_thread(.:format) posts#current_thread
posts GET /posts(.:format) posts#index
POST /posts(.:format) posts#create
new_post GET /posts/new(.:format) posts#new
edit_post GET /posts/:id/edit(.:format) posts#edit
post GET /posts/:id(.:format) posts#show
PUT /posts/:id(.:format) posts#update
DELETE /posts/:id(.:format) posts#destroy
So, how do I get rails to execute the "create_thread" function in PostsController? I have been searching over the web in the past 2 days, and trying all sorts of stuff, but none has worked for me.
Any hint or pointer would be greatly appreciated!
Thank you in advance for your help.
Try the following
resources :posts do
post :create_thread, on: :collection
end
form_tag(controller: :posts, action: :create_thread)

Rails 3 Search Action Redirects To Show?

I've ran into a weird problem in Rails. When I try and submit a search query with the following form on my Uploads controller:
<%= form_tag ({:controller => "uploads", :action => 'find_uploads'}), :method => "get" do %>
<%=h text_field_tag :search, params[:search], :id => 'search_field' %>
<br />
<%= submit_tag "Search", :style=>"display:inline;" %>
<% end %>
I get redirected to the following url and error page:
/uploads/find_uploads?utf8=✓&search=bot&commit=Search
ActiveRecord::RecordNotFound in UploadsController#show
Couldn't find Upload with id=0
My find_uploads route: get 'uploads/find_uploads' => "uploads#find_uploads"
And when I did I rake routes this is what I got:
uploads_find_uploads GET /uploads/find_uploads(.:format) {:controller=>"uploads", :action=>"find_uploads"}
Everything seems to be in order... not sure why it's not working out as expected. For debugging purposes I dropped breakpoints in both my find_uploads and show actions and neither of them were reached so this error message must be lying to me as the UploadsController show action is never called!
This form is being rendered on my index page if it counts for anything.
I think it's taking find_uploads for an id.
Declare your routes like that:
resources :uploads do
collection do
get :find_uploads
end
end
ps: currently, when you do rake routes, /uploads/find_uploads is after /uploads/:id right?

Routing error on Rails 3

I'm working on a profile page, so the config is like this:
routes.rb
=> match "user/:login(*path)" => 'users#profile', :as => :profile
rake routes
=> profile /user/:login(*path)(.:format) {:action=>"profile", :controller=>"users"}
on console
> Rails.application.routes.recognize_path("/user/example/whatever")
=> {:action=>"profile", :login=>"example", :controller=>"users", :path=>"/whatever"}
And I have a profile action in UsersControllers.
But when I use
&lt%= link_to user.name, profile_path(user.login) %>
in a view I get the error
No route matches {:login=>"example", :controller=>"users", :action=>"profile"}
What am I missing?
Thanks
Update:
Thanks for the answer and attention, Steve!
After a lot of time trying, a coworker find what I was missing: the problem was only with some logins that are emails too, with "#", ".", etc. The solution was adding to_url at params[:login] in link_to:
&lt%= link_to 'name', profile_path(params[:login].to_url) %>
Again, thanks for the attention!
Using your configuration, the route and helper seem to work fine in a Rails 3.0.5 sample app.
I verified the route helper profile_path in the Rails console:
>> app.profile_path('example')
=> "/user/example"
and checked that it worked in the view as well:
<%= link_to 'name', profile_path(params[:login]) %>
No route errors in either place. And putting <%= debug(params) %> in the view shows the path '/user/example/whatever' is being parsed correctly:
--- !map:ActiveSupport::HashWithIndifferentAccess
controller: users
action: profile
login: example
path: /whatever