matiss matiss -4 years ago 128
Ruby Question

Rails 5: AJAX modal window for namespaced controller

I'm trying to implement code from this great tutorial of AJAX modal. It works like charm on regular controllers, however it does not work when I have namespaced one.

My /config/routes.rb looks like this:

# Routes for campaigns
namespace :campaigns do
resources :campaigns, only: [:new, :create, :edit, :update]

get '/campaigns', to: 'campaigns/campaigns#index'

In /views/campaigns/campaigns/index.html.erb

<%= link_to 'New campaign', new_campaigns_campaign_path,
remote: true, class: 'btn btn-primary btn-small' %>

In /views/campaigns/campaigns/_form.html.erb

<%= form_for @campaign, remote: true, html: { role: 'form' } do |f| %>

My /views/campaigns/campaigns/new.js.erb

// Add the dialog title
$('#dialog h3').html("<i class='glyphicon glyphicon-plus'></i> Add New Campaign");

// Render the new form
$('.modal-body').html('<%= j render("form") %>');

// Show the dynamic dialog

// Set focus to the first element
$('#dialog').on('', function () {

and /views/campaigns/campaigns/create.js.erb

$('#campaigns').append('<%= j render (@campaign) %>')

are just like from the tutorial.

controllers/campaigns/campaigns_controller.rb is similar as in the tutorial, too:

#New campaign dialog
def new
@campaign =

#Create campaign
def create
@campaign = current_user.campaigns.create!(campaign_params)
respond_to do |format|
format.json { head :no_content }
format.json { render json: @campaign.errors.full_messages,
status: :unprocessable_entity }

Error I'm getting in terminal:

ActionView::Template::Error (undefined method `campaign_campaigns_index_path' for #<#<Class:0x007fd730c95ba8>:0x007fd762d32110>

It seems Rails is trying to find path I don't have. How to fix this and make it work with my namespace model, please? Thank you!

Answer Source

Execute command rake routes and check if campaign_campaigns_index_path is there. If not, maybe you have misspelled it.

EDIT: Command rake route returns all available routes that can be called with url(and _path) helper.

EDIT: Well, you could rename the nested directory to campaign(singular), and don't forget to rename the class too Campaign::CampaignsController < .... That would be the cleaner way.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download