Rails form_for wrong controller action - ruby-on-rails

Right out of the Rails Tutorial. I can't get the sign in form to call the create method. Debug shows it only calls the new action. I had no issues setting up the users which also has a database so the following was utilized:
<%= form_for #user do |f| %>
In this case, with no model, I'm doing as the tutorial suggests:
<%= form_for(:session, url: sessions_path) do |f| %>
A quick glance at rake routes shows the route is valid:
Prefix Verb URI Pattern Controller#Action
root GET / site_pages#root
about GET /about(.:format) site_pages#about
signup GET /signup(.:format) users#new
signout DELETE /signout(.:format) sessions#destroy
signin GET /signin(.:format) sessions#new
users POST /users(.:format) users#create
new_user GET /users/new(.:format) users#new
user GET /users/:id(.:format) users#show
DELETE /users/:id(.:format) users#destroy
sessions POST /sessions(.:format) sessions#create
new_session GET /sessions/new(.:format) sessions#new
session DELETE /sessions/:id(.:format) sessions#destroy
Not sure what I'm missing. Been messing with it for over an hour. Tried changing to form_tag and it's still reacting in the same way. I've edited the routes and the form in multiple ways to trigger the correct functioning with no luck.
What am I missing? Thanks.
Controller added:
def create
user = User.find_by(email: params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
#SIGN IN AND REDIRECT
else
flash.now[:danger] = "Invalid Submission. Please Try Again."
render 'new'
end
end

<div class="form-horizontal" role="form">
<%= form_for(:session, url: sessions_path) do |f| %>
<%= render 'layouts/flash' %>
<%= f.label :email %>
<%= f.text_field :email %>
<%= f.label :password %>
<%= f.password_field :password %>
<%= f.submit "Log In", class: "btn btn-primary btn-width-30" %>
<% end %>
</div>

Related

undefined local variable or method 'main_page'

In my application.html.erb I have a menu, which is displayed on every page. But I can't use 'sign out' link, an error appears.
undefined local variable or method 'main_page'
I have 'main_page' in my routes and I don't understand why it's not working.
I've tried to use 'sign out' link from my show view in the User controller's action, and it worked fine.
show.html
<% content_for :user_form do %>
<p id="notice"><%= notice %></p>
<p>
<strong>Name:</strong>
<%= #user.name %>
</p>
<p>
<strong>Email:</strong>
<%= #user.email %>
</p>
<%= link_to 'Edit', edit_user_path(#user) %>
<%= link_to 'My dates', :controller => :calendar, :action => :month_for_user %>
<%= link_to 'sign out', :controller => :sessions, :action => :destroy %>
<%end%>
Why there is an error when the link is used from application.html? Although 'My dates' link works. How can I fix it?
application.html
<div id = 'user_menu' >
<p id="notice"><%= notice %></p>
<p>
<strong>Name:</strong>
<%= current_user.name %>
</p>
<p>
<strong>Email:</strong>
<%= current_user.email %>
</p>
<%= link_to 'Edit', edit_user_path(current_user) %>
<%= link_to 'My dates', :controller => 'calendar', :action => 'month_for_user' %>
<%= link_to 'sign out', :controller => 'sessions', :action => 'destroy' %>
<% end %>
</div>
sessions_controller
def destroy
redirect_to main_page
sign_out
end
routes
Prefix Verb URI Pattern Controller#Action
meetings GET /meetings(.:format) meetings#index
POST /meetings(.:format) meetings#create
new_meeting GET /meetings/new(.:format) meetings#new
edit_meeting GET /meetings/:id/edit(.:format) meetings#edit
meeting GET /meetings/:id(.:format) meetings#show
PATCH /meetings/:id(.:format) meetings#update
PUT /meetings/:id(.:format) meetings#update
DELETE /meetings/:id(.:format) meetings#destroy
new_user GET /users/new(.:format) users#new
users GET /users(.:format) users#index
main_page GET /main_page(.:format) welcome#domain
new_session GET /sign_in(.:format) sessions#new
signout GET /sign_out(.:format) sessions#destroy
sessions POST /sessions(.:format) sessions#create
GET /sessions/new(.:format) sessions#new
edit_session GET /sessions/:id/edit(.:format) sessions#edit
session PATCH /sessions/:id(.:format) sessions#update
PUT /sessions/:id(.:format) sessions#update
DELETE /sessions/:id(.:format) sessions#destroy
GET /sessions/:id(.:format) welcome#domain
GET /users(.:format) users#index
POST /users(.:format) users#create
GET /users/new(.:format) users#new
edit_user GET /users/:id/edit(.:format) users#edit
user GET /users/:id(.:format) users#show
PATCH /users/:id(.:format) users#update
PUT /users/:id(.:format) users#update
DELETE /users/:id(.:format) users#destroy
month_for_user GET /month_for_user(.:format) calendar#month_for_user
Rails is new for me, and maybe it's a silly question, but I honestly tried to find an answer unfortunately without results. Please, help me to fix this problem! Thank you
undefined local variable or method 'main_page'
The error comes from the destroy method in your sessions_controller. It should be
def destroy
redirect_to main_page_url #or action: "main_page"
sign_out
end

No route matches [POST] in Ruby app I'm building

I'm trying to build an application that lets users create a trip with restful routing however, I'm encountering an issue when a user is logged in and they try to create a trip.
I get "No route matches [POST] "/users/8/trips/new""
These are the routes:
resources :users do
resources :trips
end
This is the trip controller:
class TripsController < ApplicationController
def new
#trip = Trip.new
end
def create
#trip = Trip.create(trip_params)
redirect_to root_path
end
end
This is the form to create a new trip. This is where I click submit and get the error:
<div class="trip_form">
<%= form_for :trip do |f| %>
<%= f.label :where, "Where?" %><br/>
<%= f.text_field :where, placeholder: "Hawaii" %><br>
<%= f.label :when, "When?" %><br/>
<%= f.text_field :when, placeholder: "#" %><br>
<%= f.label :price_per_person, "Price per person? (Approximately)" %><br/>
<%= f.text_field :price_per_person, placeholder: "$550" %><br>
<%= f.submit "Create Trip Idea"%>
<% end %>
These are the routes:
$ rake routes
Prefix Verb URI Pattern Controller#Action
user_trips GET /users/:user_id/trips(.:format) trips#index
POST /users/:user_id/trips(.:format) trips#create
new_user_trip GET /users/:user_id/trips/new(.:format) trips#new
edit_user_trip GET /users/:user_id/trips/:id/edit(.:format) trips#edit
user_trip GET /users/:user_id/trips/:id(.:format) trips#show
PATCH /users/:user_id/trips/:id(.:format) trips#update
PUT /users/:user_id/trips/:id(.:format) trips#update
DELETE /users/:user_id/trips/:id(.:format) trips#destroy
users GET /users(.:format) users#index
POST /users(.:format) users#create
new_user GET /users/new(.:format) users#new
edit_user GET /users/:id/edit(.:format) users#edit
user GET /users/:id(.:format) users#show
PATCH /users/:id(.:format) users#update
PUT /users/:id(.:format) users#update
DELETE /users/:id(.:format) users#destroy
root GET / users#index
I thought I should be able to just fill out the trip new form and when I press submit for it to
automatically communicate with the create method in the trip controller? When I do change :trip to #trip in the form I get this error:
NoMethodError in Trips#new
undefined method `trips_path'
Thanks!
<%= form_for :trip do |f| %>
should be
<%= form_for [#user, #trip] do |f| %>
and because you're using nested resources you'll need this too
# controller
def new
#user = User.find(1)
#trip = Trip.new
end
More in the documentation for form_for
There is a tiny mistake in your form_for helper. It should be:
<%= form_for #trip do |f| %>
...
The helper will look at the #trip object and see that it is a new object (= not yet saved to the database) and thus will choose POST /users/8/trips as the form action.
By not handing an ActiveRecord Object to the helper, the generated HTML form has no action, so submitting the form will POST to the current path (which is the new-path)
EDIT
In order to let the helper choose a route for the nested resource situation you have, use:
<%= form_for [current_user, #trip] do |f| %>
...
assuming that current_user is the user object you are referring to.

Rails: Routing error when rendering AJAX partial

I am encountering a routing error when I try to render a partial in an ajax call:
Routing Error
No route matches {:action=>"destroy", :controller=>"relationships", :user_id=>#<User id: 2, username: .....
Within my app, I have a list of followers for a user displayed on the profile page. Instead of paginating the followers, I would like to try to return the next offset of followers from the server through AJAX. My view already utilizes partials for displaying a list of these followers (limited to 5 records).
My goal is to use an AJAX call to return this partial with the next offset of records formated (I haven't implemented the functionality to return offset records yet - I'm just trying to get the ajax working first). The partials work fine when I visit the profile page in my browser (and view the first 5 records), the error occurs when I make the AJAX call.
Here is the form in the view where the ajax call originates:
<%= form_tag user_relationships_path(#user), method: :get, remote: true do %>
<%= submit_tag 'load more...' %>
<% end %>
Here is the route:
resources :users, only: [:index, :show, :new, :create, :edit, :update, :destroy] do
resources :relationships, only: [:create, :destroy, :index]
end
Here is my controller action (relationships#index) which responds to the request:
def index
#user = User.find_by_username(params[:user_id])
respond_to do |format|
format.js { render 'load_followers' }
end
end
The load_followers.js.erb partial:
$('ul#followers').append("<%= render 'users/following_items', users: #user.followers %>")
The users/following_items.html.erb partial:
<% users.each do |user| %>
<li class="clearfix">
<div class="box-gravatar pull-left">
<%= link_to user do %>
<%= gravatar_for user, 40 %>
<% end %>
</div>
<div class="pull-right">
<%= render 'relationships/follow', user: user %>
</div>
<%= link_to user.username, user %>
<div class="box-author">joined <%= join_date_for user %></div>
</li>
<% end %>
And finally the relationships/follow.html.erb partial:
<% unless current_user?(user) %>
<% if current_user.following? user %>
<p><%= link_to 'unfollow', user_relationship_path(user), method: :delete, class: "btn" %></p>
<% else %>
<p><%= link_to 'follow', user_relationships_path(user), method: :post, class: "btn btn-primary" %></p>
<% end %>
<% end %>
I have tracked down the offending code to the relationships/follow.html.erb partial. When that is removed, the ajax call works fine and the partial is appended to the end of the ul. Clearly it has to do with rails having an issue with the link_to to the relationships#destroy method - however, nothing I've tried seems to work.
Edit: Here are the results of running rake routes:
root / posts#index
posts_test /posts/test(.:format) posts#test
submit /submit(.:format) posts#new
signup /signup(.:format) users#new
login /login(.:format) sessions#new
logout DELETE /logout(.:format) sessions#destroy
about /about(.:format) about#index
search /search(.:format) search#index
sessions POST /sessions(.:format) sessions#create
new_session GET /sessions/new(.:format) sessions#new
session DELETE /sessions/:id(.:format) sessions#destroy
post_comments POST /posts/:post_id/comments(.:format) comments#create
post_votes POST /posts/:post_id/votes(.:format) votes#create
posts GET /posts(.:format) posts#index
POST /posts(.:format) posts#create
new_post GET /posts/new(.:format) posts#new
post GET /posts/:id(.:format) posts#show
user_relationships GET /users/:user_id/relationships(.:format) relationships#index
POST /users/:user_id/relationships(.:format) relationships#create
new_user_relationship GET /users/:user_id/relationships/new(.:format) relationships#new
edit_user_relationship GET /users/:user_id/relationships/:id/edit(.:format) relationships#edit
user_relationship GET /users/:user_id/relationships/:id(.:format) relationships#show
PUT /users/:user_id/relationships/:id(.:format) relationships#update
DELETE /users/:user_id/relationships/:id(.:format) relationships#destroy
users GET /users(.:format) users#index
POST /users(.:format) users#create
new_user GET /users/new(.:format) users#new
edit_user GET /users/:id/edit(.:format) users#edit
user GET /users/:id(.:format) users#show
PUT /users/:id(.:format) users#update
DELETE /users/:id(.:format) users#destroy
categories GET /categories(.:format) categories#index
POST /categories(.:format) categories#create
new_category GET /categories/new(.:format) categories#new
category GET /categories/:id(.:format) categories#show
/:category(.:format) posts#index
Thanks!
Notices your rake routes outputted this line:
DELETE /users/:user_id/relationships/:id(.:format)
This means your named route user_relationship is expecting both user and relationship IDs. Reason being, relationship is a nested resource of user.
So for instance you currently have this in your link to:
= link_to 'unfollow', user_relationship_path(user), method: :delete, class: "btn"
Instead it should be something like:
= link_to 'unfollow', user_relationship_path(user, relationship), method: :delete, class: "btn"

Route failing using STI

First SO post, but I've read so many. I'm new to Rails and building first site since studying Hartl's RailsTutorial.
My issue is routing using STI. I believe the routes are set up correctly, but the subclass Kid doesn't find a "show" route.
Class inheritance using STI
class User < ActiveRecord::Base
class Kid < User
Kid Controller
def show
#kid = Kid.find(params[:id])
end
User Controller create
def create
#user = User.new(params[:user])
if #user.save
flash[:success] = "Welcome to kidtunes!"
if (#user.type = "Kid")
***redirect_to #kid***
else
redirect_to #parent
end
else
render 'new'
end
routes.rb
resources :users, :kids, :parents
root to: 'static_pages#home'
match '/help', to: 'static_pages#help'
match '/contact', to: 'static_pages#contact'
match '/signup', to: 'users#new'
Results in:
kids_new GET /kids/new(.:format) kids#new
users GET /users(.:format) users#index
POST /users(.:format) users#create
new_user GET /users/new(.:format) users#new
edit_user GET /users/:id/edit(.:format) users#edit
user GET /users/:id(.:format) users#show
PUT /users/:id(.:format) users#update
DELETE /users/:id(.:format) users#destroy
kids GET /kids(.:format) kids#index
POST /kids(.:format) kids#create
new_kid GET /kids/new(.:format) kids#new
edit_kid GET /kids/:id/edit(.:format) kids#edit
kid GET /kids/:id(.:format) kids#show
PUT /kids/:id(.:format) kids#update
DELETE /kids/:id(.:format) kids#destroy
parents GET /parents(.:format) parents#index
POST /parents(.:format) parents#create
new_parent GET /parents/new(.:format) parents#new
edit_parent GET /parents/:id/edit(.:format) parents#edit
parent GET /parents/:id(.:format) parents#show
PUT /parents/:id(.:format) parents#update
DELETE /parents/:id(.:format) parents#destroy
root / static_pages#home
help /help(.:format) static_pages#help
contact /contact(.:format) static_pages#contact
signup /signup(.:format) users#new
Error
I get the following on redirect_to #kid
ActionController::ActionControllerError (Cannot redirect to nil!):
app/controllers/users_controller.rb:16:in `create'
I feel like I've checked everything I can check, but I'm still missing something. #kid should properly redirect to the kids#show route. I'm not sure if I have a poorly crafted single table inheritance or a basic routing issue.
thanks in advance.
-John
Form
This form is used in users/new.html.erb and it creates the User.
<div class="row">
<div class="span5 offset2">
<%= form_for(#user) do |f| %>
<%= render 'shared/error_messages' %>
<%= f.label :fname, "First Name" %>
<%= f.text_field :fname %>
<%= f.label :lname, "Last Name" %>
<%= f.text_field :lname %>
<%= f.label :email %>
<%= f.text_field :email %>
<%= f.label :type, "Are you a Kid or Parent?" %>
<%= f.select :type, [['Kid','Kid'],['Parent','Parent']] %>
<%= f.label :password %>
<%= f.password_field :password %>
<%= f.label :password_confirmation, "Confirmation" %>
<%= f.password_field :password_confirmation %>
<%= f.submit "Create my account", class: "btn btn-large btn-primary" %>
<% end %>
Have you defined/assigned values to the #kid or #parent variables? If not, they will be nil, and you'll get the cannot redirect to nil error you've included in your question.
Please include the full code for the create action. Otherwise we're left to trust (rather than read for ourselves) precisely what's happening in the redirect.
Your redirects might also need some work. For example, you could do:
if (#user.is_a? Kid)
redirect_to kid_path(#user)
else
redirect_to parent_path(#user)
end
...or something very similar to that.
First thing I noticed is that you're using = instead of ==:
if (#user.type = "Kid")
I think it's nicer to test it like that:
if #user.is_a? Kid
Can you show us how you set #kid and #parent?

Error (RoR Tutorial) -dropdown not firing w/bootstrap- session destroy path incorrect?

Error in Rails Tutorial (Hartl) v3.2
I'm on chapter 8 and all tests pass correctly prior to the exercises. Except two issues (I think they're related).
The dropdown-menu is not firing with bootstrap as the session destroy path appears to be incorrect. I'm also attempting to use the form_tag in place of the form_for tag and I keep getting the following error:
undefined method `[]' for nil:NilClass
Here is the new_html.erb under app/views/sessions:
<% provide(:title, "Sign in") %>
<h1>Sign in</h1>
<div class="row">
<div class="span6 offset3">
<%= form_tag sessions_path do %>
<%= label_tag :email %>
<%= text_field_tag :email %>
<%= label_tag :password %>
<%= password_field_tag :password %>
<%= submit_tag "Sign in", :class => "btn btn-large btn-primary" %>
<% end %>
<p>New user? <%= link_to "Sign up now!", signup_path %></p>
</div>
</div>
Here's the sessions_controller.rb:
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by_email(params[:session][:email])
if user && user.authenticate(params[:session][:password])
sign_in user
redirect_to user
else
flash.now[:error] = 'Invalid email/password combination' # Not quite right!
render 'new'
end
end
def destroy
sign_out
redirect_to root_path
end
end
Finally, here's the rake routes output:
users GET /users(.:format) users#index
POST /users(.:format) users#create
new_user GET /users/new(.:format) users#new
edit_user GET /users/:id/edit(.:format) users#edit
user GET /users/:id(.:format) users#show
PUT /users/:id(.:format) users#update
DELETE /users/:id(.:format) users#destroy
sessions POST /sessions(.:format) sessions#create
new_session GET /sessions/new(.:format) sessions#new
session DELETE /sessions/:id(.:format) sessions#destroy
signup /signup(.:format) users#new
signin /signin(.:format) sessions#new
signout DELETE /signout(.:format) sessions#destroy
help /help(.:format) static_pages#help
about /about(.:format) static_pages#about
contact /contact(.:format) static_pages#contact
root / static_pages#home
Any help would be great.
Edit:
cbright had it. I had to modify the sessions_controller. The following two lines work as intended.
user = User.find_by_email(params[:email])
if user && user.authenticate(params[:password])
The session symbol used with form_for is no longer being used, so replace params[:session][:email] and params[:session][:password] with params[:email] params[:password].

Resources