Question

I'm having severe difficulty getting a custom route to work on a fairly simple Rails 4 app that I'm putting together to study routing and Unobtrusive JavaScript.

Right now I'm having trouble just getting my show page to render after having added my custom route. I see the following error:

NoMethodError in Posts#show
Showing /home/tom/rails/blog/app/views/posts/_post.html.erb where line #18 raised:

undefined method `switch_post_path' for #<#<Class:0x007f55a89ac680>:0x007f55a89ab898>

I have a simple show page for blog posts that I want to display post info on through AJAX without refreshing the entire page.

app/views/posts/show.html.erb:

<h1>View Post</h1>

<div id="post_info">
 <%= render @post %>
</div>

This uses the following partial.

app/views/posts/_post.html.erb:

<p>
  <strong>Content:</strong>
  <%= @post.content %>
</p>

<div id="navs">
    <%= link_to "Last", switch_post_path(@all_posts[@all_posts.index(@post) -1]), remote: true %>
    <%= link_to "Next", switch_post_path(@all_posts[@all_posts.index(@post) +1]), remote: true %>
    <%= link_to 'Back', posts_path %>
</div>

My routes file is pretty simple.

config/routes.rb:

Blog::Application.routes.draw do
  resources :posts
  get 'switch_post/:id', to: 'posts#switch_post'
end

There is a corresponding method in my controller

app/controllers/posts_controller.rb:

def show
  @post = Post.find(params[:id])
  @all_posts = Post.all
end

def switch_post
  @post = Post.find(params[:id])
  @all_posts = Post.all
end

If this works, it should fire a JavaScript file:

switch_post.js:

$("#post_info").html("<%= escape_javascript(render @post) %>");

If you've read this far, I appreciate your time. Where am I going wrong?

Was it helpful?

Solution

Change your routing for switch_post to be a member route instead like this:

Blog::Application.routes.draw do
  resources :posts do
     get 'switch_post'
  end
end

Then in your route helpers on the view side you want to use post_switch_post_path

Lastly, in your controller you will now reference the post with params[:post_id] like this:

def switch_post
  @post = Post.find(params[:post_id])
  @all_posts = Post.all
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top