How to fix an error with routing in rails app? - ruby-on-rails

I have the following in my routes.rb file:
match "/service/:product" => "products#show_name"
match "/products/custom/" => "products#custom"
match "/products/customform" => "products#customform"
match "/categories" => "products#categories"
match "/search" => "products#search"
match "/about" => "products#about"
get 'category/:tag', to: 'products#category', as: :tag
resources :products do
resources :reviews
end
I am trying to access the url "/service/birchbox". When I do, I get an error saying
No route matches {:action=>"edit", :controller=>"products"}
Any advice on how to fix this? I am trying to get this url to go to the first route listed (to the controller products#show_name but is going to edit for some reason).
Here is some more information I'm seeing in the console. It seems like it's going to show_name but I keep getting an error.
Processing by ProductsController#show_name as HTML
Parameters: {"product"=>"birchbox"}
Product Load (0.2ms) SELECT "products".* FROM "products" WHERE "products"."slug" = 'birchbox' LIMIT 1
(0.1ms) SELECT COUNT(*) FROM "reviews" WHERE "reviews"."product_id" = 14
ActsAsTaggableOn::Tag Load (0.1ms) SELECT "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."taggable_id" = 14 AND "taggings"."taggable_type" = 'Product' AND (taggings.context = 'tags' AND taggings.tagger_id IS NULL)
Rendered products/show_name.html.erb within layouts/application (97.3ms)
Completed 500 Internal Server Error in 164ms
ActionController::RoutingError (No route matches {:action=>"edit", :controller=>"products"}):
app/views/products/show_name.html.erb:42:in `_app_views_products_show_name_html_erb___2110533700820522490_70197663436420'

It seems that in views/products/show_name.html.erb at line 42 you have something like this:
<%= edit_product_path %>
And this route doesn't exist. edit route requires product id. Try this:
<%= edit_product_path(#product) %>

Related

link_to nested resource route can't find ID

The link_to in my user name is creating an error and I don't know why.
Error:
Couldn't find StripeAccount without an ID
Controller:
this is inside a separate controller from the StripeAccount controller
def settings
#user = current_user.id
#stripe_account = StripeAccount.find(params[:stripe_account_id])
end
I have tried "#stripe_account = StripeAccount.find(params[:id])" with the same error
View:
<%= link_to user_stripe_account_path(#user, #stripe_account) %>
I have tried using #stripe_account.id, etc.
Models:
stripe_account::
belongs_to :user, optional: true
user::
has_one :stripe_account
Routes:
resources :users do
resources :stripe_accounts
end
Error when i try loading the /settings page:
Here's the CMD from when I use: #stripe_account = StripeAccount.find(params[:stripe_account_id])
app/controllers/dashboard_controller.rb:18:in `settings'
Started GET "/settings" for 127.0.0.1 at 2018-11-17 06:27:04 -0500
Processing by DashboardController#settings as HTML
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ? [["id", 2], ["LIMIT", 1]]
↳ app/controllers/dashboard_controller.rb:17
Completed 404 Not Found in 3ms (ActiveRecord: 0.3ms)
ActiveRecord::RecordNotFound (Couldn't find StripeAccount without an ID):
app/controllers/dashboard_controller.rb:18:in `settings'
When i use #stripe_account = StripeAccount.find(params[:id])
ActiveRecord::RecordNotFound (Couldn't find StripeAccount without an ID):
app/controllers/dashboard_controller.rb:18:in `settings'
Started GET "/settings" for 127.0.0.1 at 2018-11-17 06:28:21 -0500
Processing by DashboardController#settings as HTML
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ? [["id", 2], ["LIMIT", 1]]
↳ app/controllers/dashboard_controller.rb:17
Completed 404 Not Found in 3ms (ActiveRecord: 0.3ms)
ActiveRecord::RecordNotFound (Couldn't find StripeAccount without an ID):
app/controllers/dashboard_controller.rb:18:in `settings'
What am i doing incorrectly?
The only issue i can think of that may be happening is rails/ruby is finding the API ID from stripe_account, which contains a bunch of information from stripe... if so, is there a way i can specifically state using the ID from the table?
You should be able to do #stripe_account = current_user.stripe_account if you wan't to set the variable to the current_user's stripe account (you have no id param on the request). And I recommend you to use #user = current_user or #user_id = current_user.id since it's confusing to read a variable named #user that has an integer value.
When you define "StripeAccount belongs_to User", by default (it's the convention) ActiveRecord looks for a user_id column on stripe_accounts table.
I'd recommend you to read this https://guides.rubyonrails.org/association_basics.html. It explains all types of associations and you can configure your associations even if they are not conventional (different class names, no _id column, etc).
After many attempts, i got one way to work. I'm not sure how efficient this is and i will explore more options.
This ended up working how i wanted to:
#stripe_account = StripeAccount.find_by(params[:id])
The key was using ".find_by" and not ".find". This allows the link_to to operate and goes to the right location.

Rails Custom Route Redirecting to Show

I've created a custom route make_winner_pick but every time I click the link to follow the path the controller defaults to the show action. I can't understand what I'm doing wrong and it's driving me nuts
routes.rb
resources :league_members
get "league_members/make_winner_pick" => "league_members#make_winner_pick", :as => :make_winner_pick
Where the path is called
<%= link_to 'Join League', make_winner_pick_path(league: league.id), method: :get %>
The console
Started GET "/league_members/make_winner_pick?league=3" for 127.0.0.1 at 2015-08-29 01:33:56 +0100
Processing by LeagueMembersController#show as HTML
Parameters: {"league"=>"3", "id"=>"make_winner_pick"}
User Load (0.9ms) SELECT "users".* FROM "users" WHERE "users"."id" = 2 ORDER BY "users"."id" ASC LIMIT 1
LeagueMember Load (0.5ms) SELECT "league_members".* FROM "league_members" WHERE "league_members"."id" = $1 ORDER BY "league_members"."id" ASC LIMIT 1 [["id", 0]]
Completed 404 Not Found in 5ms
ActiveRecord::RecordNotFound (Couldn't find LeagueMember with 'id'=make_winner_pick):
app/controllers/league_members_controller.rb:68:in `set_league_member'
Can anyone tell me why my custom route is not being fired and Rails is defaulting to the #show action? For some reason it appears to be looking for a league_member with an id of make_winner_pick
Thanks for looking.
Try nest your route within the resource:
resources :league_members do
collection do
get "make_winner_pick" => "league_members#make_winner_pick", :as => :make_winner_pick
end
end
Because rails recognized your route make_winner_pick as an id.
it should be:
<%= link_to 'Join League', league_members_make_winner_pick_path(league: league.id), method: :get %>

Routes work in Development But not in Production

Weird Error. I have some routes that work perfectly during development but once i deploy and try to access them it comes up with page does not Exist error
I have the following routes.rb file:
TransportUnl::Application.routes.draw do
resources :trucks
resources :shipments do
collection do
get :autocomplete_location_cs
end
end
devise_for :users do
get '/users/sign_in' => 'devise/sessions#new'
get '/users/sign_out' => 'devise/sessions#destroy'
end
root :to => 'info#index'
resources :info do
collection do
get 'about'
get 'contact'
get 'you_dont_have_a_full_account'
get 'help'
end
member do
get 'index'
end
end
resources :companies
end
Not everything is setup yet. but i am getting a page not found error when i go to:
www.website.com/shipments
www.website.com/trucks
as well as others in production. The main index page works and you can login but these pages come up not found.
Production
Development
Production.log
Started GET "/shipments" for 108.235.52.160 at 2015-06-22 13:09:03 -0500
Processing by ShipmentsController#index as HTML
[1m[35m (0.6ms)[0m SELECT MAX("shipments"."price") AS max_id FROM "shipments"
[1m[36mShipment Load (0.3ms)[0m [1mSELECT "shipments".* FROM "shipments" [0m
Rendered shipments/_nav.html.erb (0.6ms)
Rendered shipments/_search_table.html.erb (0.1ms)
Rendered shipments/index.html.erb within layouts/application (1.2ms)
[1m[35mUser Load (0.5ms)[0m SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
Rendered shared/_header.html.erb (5.0ms)
Completed 500 Internal Server Error in 12ms
ActionController::RoutingError (No route matches {:action=>"edit", :controller=>"companies"}):
app/views/shared/_header.html.erb:78:in `_app_views_shared__header_html_erb___2847381188393053217_232073740'
app/views/layouts/application.html.erb:17:in `_app_views_layouts_application_html_erb__4421904906041360553_230384600'
app/controllers/shipments_controller.rb:7:in `index'
Started GET "/info/about" for 157.55.39.229 at 2015-06-22 13:10:29 -0500
Processing by InfoController#about as */*
Rendered info/about.html.erb within layouts/application (5.7ms)
Rendered shared/_header.html.erb (3.8ms)
[1m[36m (4.3ms)[0m [1mSELECT * FROM geometry_columns WHERE f_table_name='shipments'[0m
[1m[35mShipment Load (0.9ms)[0m SELECT "shipments".* FROM "shipments" ORDER BY id DESC LIMIT 3
Rendered shared/_footer.html.erb (31.6ms)
Completed 200 OK in 177ms (Views: 151.1ms | ActiveRecord: 25.6ms)
the Link is created like this:
<%= link_to "My Account", edit_company_path(current_user.company_id) %>
As you can see from logs, you got error page because of line 78 of app/views/shared/_header.html.erb file.
In this piece of code, where you creating link
<%= link_to "My Account", edit_company_path(current_user.company_id) %>
Check if company_id is not nil for that particular user. I'm pretty sure it's nil in your case.
As you can see from error logs, it tries to get action edit as collection action of companies controller - companies/edit. You don't have this route defined. But if current user will have company_id, the link will be built correctly and you wont receive an error.

Changing boolean with link_to Error

This is what it said in my local server:
Started GET "/hunt/one" for 127.0.0.1 at 2015-04-14 23:54:47 -0700
ActiveRecord::SchemaMigration Load (0.4ms) SELECT "schema_migrations".* FROM "schema_migrations"
Processing by HuntController#one as HTML
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1
Rendered hunt/one.html.erb (281.8ms)
Completed 500 Internal Server Error in 406ms
ActionView::Template::Error (No route matches {:action=>"update_clue1", :controller=>"clue", :id=>nil} missing required keys: [:id]):
In my controller
def update_clue1
#clue = Clue.find(1)
#clue.update_attributes(clue1: true)
redirect_to "/home/clues"
end
In my routes
resources :clue do
member do
get :update_clue1
put :update_clue1
end
end
In my view
<%= link_to "See next clue", update_clue1_clue_path(#clue), method: :put, class: "btn btn-default" %>
Thanks for the help!
EDIT
New Error /Users/coleschiffer/Code/rp/protected-beyond-7706/app/controllers/hunt_controller.rb:14: class/module name must be CONSTANT
Here is the hunt controller
def update_clue1
#clue = Clue.find(1)
#clue.update_attributes(clue1: true)
redirect_to "/home/clues "
end

Params passed into URL Ruby on Rails

I'm having some issue with my form_tag search functionality is not redirecting me properly to a place where I can see the results of my search.
It was working fine yesterday, Once the submit button of the search is clicked, a get request to the pets controller search method is fired and then I was redirected to the results.html.erb page where the results are displayed.
The problem is that now when I submit the search, it's just refreshing the page (index.html.erb) and my params are passed to the URL but none of the "pets" i searched for are displayed.
http://localhost:3000/?utf8=%E2%9C%93&authenticity_token=iDXugIhTyjknCMpPh2P5x7voNMSQ3Y7Aa1HIZPA7xqZ9Oj4CAuVc5eJPqfE1CLwxXAsCebgPuNWqpOk381TlvQ%3D%3D&pets%5Bzip_code%5D=10019&pets%5Bspecies%5D=Cat&pets%5Bbreed%5D=&pets%5Bage%5D=&pets%5Bsex%5D=&pets%5Bsize%5D=&commit=Find+Pets%21
Before it was just redirecting me the results page localhost:3000/results
Here is my pets controller
class PetsController < ApplicationController
def index #index page will render search form
#pet = Pet.new
#send form data in params to create
end
def search
#pets = Pet.where(clean_params)
render :results
end
private
def thinned_params
params["pets"].delete_if {|k, v| v.empty?}
end
def clean_params
thinned_params.permit(:species, :zip_code, :sex, :size, :breed, :age)
end
end
My form_tag in welcome#index:
<form class="form-horizontal">
<%= form_tag :controller => 'pets', :action => 'search', :method => 'get' do %>
<%= label_tag('pets[zip_code]', "Zipcode") %>
<%= text_field_tag('pets[zip_code]') %>
<%= label_tag('pets[species]', "Type") %>
<%= select_tag('pets[species]', options_for_select([["Dog","Dog"],["Cat","Cat"],["Rabbit", "Rabbit"], ["Small & Furry","Smallfurry"],["Horse", "Horse"],["Pig", "Pig"],["Reptile", "Reptile"],["Bird", "Bird"],["Barnyard", "Barnyard"]])) %>
<%= label_tag('pets[breed]', "Breed") %>
<%= text_field_tag('pets[breed]', nil, class: 'typeahead') %>
<%= label_tag('pets[age]', "Age") %>
<%= select_tag('pets[age]', options_for_select([["None",""],["Baby","Baby"],["Young","Young"],["Adult", "Adult"], ["Senior","Senior"]])) %>
<%= label_tag('pets[sex]', "Gender") %>
<%= select_tag('pets[sex]', options_for_select([["None",""],["Male","M"],["Female","F"]])) %>
<%= label_tag('pets[size]', "Size") %>
<%= select_tag('pets[size]', options_for_select([["None",""],["Small","S"],["Medium","M"], ["Large", "L"], ["Xtra Large", "XL"]])) %>
<%= submit_tag "Find Pets!" %>
<%end%>
</form>
And finally...my routes.rb
Rails.application.routes.draw do
devise_for :users
resources :users
# resources :pets
root 'welcome#index'
get '/pets' => 'pets#index'
post '/pets/search' => 'pets#search'
resources :favorite_pets
get '/my_pets' => 'users#my_pets'
end
So my question is why is my params passed to the URL when it should just hit the search method in the pets controller and redirect me to the results page displaying the info?
Second question, obviously, what can I do to fix this problem?
UPDATE
here is the output of my console when the "search" button is clicked.
Started GET "/?utf8=%E2%9C%93&authenticity_token=NgVe%2Fe5i6sn8ijRmgcvOezp62KlymrNRWPJfFNOVJ54ChWpZf8JYTm%2Fk%2FeHdDsvcgzdBYe%2BjUX5jiz2JeALEpQ%3D%3D&pets%5Bzip_code%5D=10019&pets%5Bspecies%5D=Cat&pets%5Bbreed%5D=&pets%5Bage%5D=&pets%5Bsex%5D=&pets%5Bsize%5D=&commit=Find+Pets%21" for ::1 at 2015-03-15 15:54:34 -0400
Processing by WelcomeController#index as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"NgVe/e5i6sn8ijRmgcvOezp62KlymrNRWPJfFNOVJ54ChWpZf8JYTm/k/eHdDsvcgzdBYe+jUX5jiz2JeALEpQ==", "pets"=>{"zip_code"=>"10019", "species"=>"Cat", "breed"=>"", "age"=>"", "sex"=>"", "size"=>""}, "commit"=>"Find Pets!"}
Pet Load (0.7ms) SELECT "pets".* FROM "pets"
CACHE (0.0ms) SELECT "pets".* FROM "pets"
CACHE (0.0ms) SELECT "pets".* FROM "pets"
CACHE (0.0ms) SELECT "pets".* FROM "pets"
Breed Load (0.2ms) SELECT "breeds".* FROM "breeds" INNER JOIN "pet_breeds" ON "breeds"."id" = "pet_breeds"."breed_id" WHERE "pet_breeds"."pet_id" = ? [["pet_id", 71]]
Shelter Load (0.1ms) SELECT "shelters".* FROM "shelters" WHERE "shelters"."id" = ? LIMIT 1 [["id", 26]]
Breed Load (0.3ms) SELECT "breeds".* FROM "breeds" INNER JOIN "pet_breeds" ON "breeds"."id" = "pet_breeds"."breed_id" WHERE "pet_breeds"."pet_id" = ? [["pet_id", 73]]
CACHE (0.0ms) SELECT "shelters".* FROM "shelters" WHERE "shelters"."id" = ? LIMIT 1 [["id", "26"]]
Breed Load (0.1ms) SELECT "breeds".* FROM "breeds" INNER JOIN "pet_breeds" ON "breeds"."id" = "pet_breeds"."breed_id" WHERE "pet_breeds"."pet_id" = ? [["pet_id", 41]]
Shelter Load (0.1ms) SELECT "shelters".* FROM "shelters" WHERE "shelters"."id" = ? LIMIT 1 [["id", 16]]
Breed Load (0.1ms) SELECT "breeds".* FROM "breeds" INNER JOIN "pet_breeds" ON "breeds"."id" = "pet_breeds"."breed_id" WHERE "pet_breeds"."pet_id" = ? [["pet_id", 9]]
Shelter Load (0.1ms) SELECT "shelters".* FROM "shelters" WHERE "shelters"."id" = ? LIMIT 1 [["id", 5]]
Rendered welcome/index.html.erb within layouts/application (20.9ms)
Completed 200 OK in 127ms (Views: 125.2ms | ActiveRecord: 1.6ms)
Rake Routes
https://slack-files.com/files-pub/T02MD9XTF-F041PKBE2-532b801cb1/-.txt
According to your routes file, the search action only accepts POST (not GET):
post '/pets/search' => 'pets#search'
That seems appropriate, so just change your form action to use the POST method:
form_tag :controller => 'pets', :action => 'search', :method => :post
Your route is POST, but that makes no sense, are you trying to update or replace pets? No, you getting a list of pets. You are already calling a GET request in your form, so you can leave that, and change
post '/pets/search' => 'pets#search' to get '/pets/search' => 'pets#search'
More information on get and post.

Resources