Unexpected nested route generated using Rails url_for helper - ruby-on-rails

I'm using Rails 5 and my routes look something like:
Rails.application.routes.draw do
namespace :admin do
namespace :moderation do
resources :templates
end
resources :users, except: [:new, :create] do
namespace :moderation do
resources :messages, only: [:index, :show, :new, :create, :update, :edit] do
resources :message_replies, only: [:create, :edit, :update]
end
resources :templates
end
end
root "home#index"
end
end
I have models/admin/user.rb:
module Admin
class User < ::User
end
end
And models/admin/moderation/template.rb:
module Admin
module Moderation
class Template < ::Moderation::Template
end
end
end
Now when I try to generate the right route using url_for helper:
2.4.1 (main):0 > admin_user = Admin::User.first
2.4.1 (main):0 > admin_moderation_template = Admin::Moderation::Template.first
2.4.1 (main):0 > url_for([admin_user, admin_moderation_template])
NoMethodError: undefined method `admin_user_admin_moderation_template_url' for main:Object
Instead of getting admin_user_moderation_template_url I got admin_user_admin_moderation_template_url. Any help of how should I generate the right route in this case?

I wonder if you could resolve using this xxx_url() helper. In your case it'd be:
admin_user_moderation_template_url( user_id: admin_user.id, id: admin_moderation_template.id )
.
EDIT
Unfortunately I cannot try it as I would have to build the app you are working on. But as stated in this answer you can use symbols to create admin_user_moderation_template_url.
Try to run the following line and tell me if it works (I'm not sure user_id is in the right position, but it might work).
url_for( [:admin, :user, :moderation, :template, user_id: admin_user.id, id: admin_moderation_template.id ])
You need also an association between User and Template to be able to link them.

Related

Routing Error uninitialized constant Meetups

I am currently stuck getting a Routing Error for uninitialized constant Meetups
class MeetupsController < ApplicationController
before_action :set_meetup, only: [:edit, :update, :destroy]
def create
#meetup = Meetup.new(host: current_user)
#meetup.save
redirect_to meetup_create_path(Wicked::FIRST_STEP, meetup_id: #meetup.id)
end
end
This is my create function inside my MeetupsController, as you can see the controller name is plural and the file name is 'meetups_controller.rb'
Below is my routes.rb
Rails.application.routes.draw do
devise_for :users
resources :users
resources :meetups, except: [:show] do
resources :create, controller: 'meetups/setup'
resources :participations, only: [:new]
member do
get "create/review", to: 'meetups/setup#review'
end
end
root to: 'pages#home'
get 'join_meetup', to: 'pages#join_meetup'
get 'events', to: 'pages#events'
get 'landing', to: 'pages#landing'
end
Any help would be greatly appreciated.
Error trace would be more helpful.
But looking at resources :create, controller: 'meetups/setup' in routes file, I could guess that the Rails application is Expecting namespaced controller as Meetups::SetupController.
So you need to change your controller accordingly. You need to create a namespaced controller or may be a scoped controller.
Reference: http://guides.rubyonrails.org/routing.html#controller-namespaces-and-routing

Record Not found Couldn't find Contrato with id

I'm trying to export a docx file using caracal but I'm getting a routing error, but everything seems to be okay.
I did this 3 days ago exactly like now and worked, now I'm getting an error.
Routes.rb
Rails.application.routes.draw do
get 'grayscale/index'
devise_for :users, path: '', path_names: {sign_in: 'login', sign_out: 'logout', sign_up: 'registrar'}
resources :contratos
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root 'contratos#index'
get 'contratos/page'
end
contratos_controller.rb
class ContratosController < ApplicationController
before_action :authenticate_user!
before_action :set_contrato, only: [:show, :edit, :update, :destroy, :export, :page]
access all: [:show, :index], user: {except: [:destroy, :new, :create, :update, :edit]}, site_admin: :all
require './lib/generate_pdf'
# GET /contratos
# GET /contratos.json
def index
#contratos = Contrato.all
end
# GET /contratos/1
# GET /contratos/1.json
def show
end
# GET /contratos/new
def new
#contrato = Contrato.new
end
# GET /contratos/1/edit
def edit
end
def page
Caracal::Document.save(Rails.root.join("public", "example.docx")) do |docx|
# page 1
docx.h1 'Page 1 Header'
docx.hr
docx.p
docx.h2 'Section 1'
docx.p 'Lorem ipsum dolor....'
docx.p
end
path = File.join(Rails.root, "public")
send_file(File.join(path, "example.docx")
end
show.html.erb
<%= link_to 'Generate Docx', contratos_page_path %>
The full error
ActiveRecord::RecordNotFound in ContratosController#show
Couldn't find Contrato with 'id'=page
def set_contrato
#contrato = Contrato.find(params[:id])
end
This is a very common beginner issue which is due to the fact that routes have precedence in the order they are declared (thus the comment on top of routes.rb).
Since resources :contratos already defines a GET /contratos/:id route it will always match the request for GET /contratos/page to contratos#show. Rails does not assume that your ids are numerical when routing. These paths will all match the GET /contratos/:id route:
GET /contratos/1
GET /contratos/page
GET /contratos/page?foo=bar
GET /contratos/foo-bar-baz
GET /contratos/alksjd-usfiugi%-dfgd
But these will not:
GET /contratos/new # declared before the show route
GET /contratos/1/foo
GET /contratos/foo/bar
You can fix this by moving your custom route to the top:
get 'contratos/page'
resources :contratos
But there is a better Rails way of adding additional restful actions to a resource:
resources :contratos do
get :page, on: :collection
end

Rails doesn't create route for "controller#new" action

I get a weird behavior when trying to do a super easy task:
adding
resources :something do
...
end
to the routes.rb generates all routes except #new.
when trying to browse 'localhost:3001/somethings/new' it handled by #show action.
I'm using rails 5.1.4 version. Any ideas?
======== UPDATE ========
I added s and still have the same problem: Here is the full code example and the result:
namespace :api do
namespace :webapp do
resources :user do
resources :documents
end
end
end
I was able to make it work when added:
resources :documents , only: [:show, :index, :update, :edit, :new, :create]

rspec ActionController::UrlGenerationError for create action in namespaced admin that is nested

I'm getting this error in my controller spec for my create action
No route matches {:action=>"create", :assessment=>{:course_id=>"1", :curriculum_id=>"1"}, :controller=>"admin/assessments"}
Here is my controller spec:
it "sets the flash success" do
set_current_admin
course = Fabricate(:course)
post :create, assessment: { course_id: course.id, curriculum_id: course.curriculum.id }
expect(flash[:success]).not_to be_blank
end
The error occurs on the post :create.. line.
Here is my create action for assessments:
def create
#assessment = Assessment.new(assessment_params.merge!(course_id: Course.find(params[:course_id]).id))
if #assessment.save
flash[:success] = "You have created your assessment."
redirect_to curriculum_course_assessment_path(#assessment.course.curriculum, #assessment.course, #assessment)
else
...
end
end
And, here is my routing for the assessments:
resources :curriculums, only: [:index, :show] do
resources :courses, only: [:show] do
resources :assessments, only: [:show]
namespace :admin do
resources :assessments, only: [:index, :new, :create, :edit, :update]
end
end
end
Here is the line from my rake routes...
POST /curriculums/:curriculum_id/courses/:course_id/admin/assessments(.:format) admin/assessments#create
When I actually run the create action in the browser, it works fine, so I'm guessing that it's a problem with my spec's syntax. Any advice on this would be much appreciated. (I realize that I'm double-nesting by resources here which is not generally the best practice, but I couldn't find any other way to access the curriculums & courses params.)
You're nesting the course_id and curriculum_id parameters inside an assessment hash - in the route, they are not nested.

Routing Error : uninitialized constant when split controller routes into namespaced route

I have routes like this below. Is it possible if I have routes like this ?
#config/routes
resources :subscribers, only: [:index, :show]
namespace :admin do
resources :subscribers, only: [:new, :edit, :update, :create, :destroy]
end
I have tried to run rake routes and the result is
admin_subscribers POST /admin/subscribers(.:format) admin/subscribers#create
new_admin_subscriber GET /admin/subscribers/new(.:format) admin/subscribers#new
edit_admin_subscriber GET /admin/subscribers/:id/edit(.:format) admin/subscribers#edit
admin_subscriber PUT /admin/subscribers/:id(.:format) admin/subscribers#update
DELETE /admin/subscribers/:id(.:format) admin/subscribers#destroy
subscribers GET /subscribers(.:format) subscribers#index
subscriber GET /subscribers/:id(.:format) subscribers#show
the result was appropriate with my expectation, but when i run my RSpec i got errors
Routing Error
uninitialized constant Admin::SubscribersController
Try running rake routes for more information on available routes.
I added this code below in my Rspec Helper too
#spec/spec_helper.rb
Spork.each_run do
###
if /spork/i =~ $0 || RSpec.configuration.drb?
ActiveSupport::Dependencies.clear
end
###
end
But, if I fire my browser to htt**://l*alhost:3000/admin/subscribers/new, everything is fine.
Am I missing something ?
As stated in the docs
If you want to route /admin/subscribers to SubscribersController (without the Admin:: module prefix), you could use scope instead of namespace
#config/routes
resources :subscribers, only: [:index, :show]
scope "/admin" do
resources :subscribers, only: [:new, :edit, :update, :create, :destroy]
end
I don't think there's much need for you to namespace this under admin. You could just fill in all the actions on SubscribersController and set the permissions on create, update etc. appropriately.

Resources