Search code examples
ruby-on-railsrouteslink-to

Rails route to a resource


I'm building a Rails app that is a podcast directory. I have Podcasts and Episodes. Episode belongs to Podcast and Podcast has many Episodes. On the home page I want to show the last 5 episodes that have been created and link to them.

I have it working with this, though this is obviously not the way to do it:

<% @episodes.each do |episode| %>
  <%# link_to episode do %>
    <a href="http://example.com/podcasts/<%= episode.podcast_id %>/episodes/<%= episode.id %>" class="tt-case-title c-h5"><%= episode.title %></a>
  <%# end %>
<% end %>

The link_to is commented out because that's part of my problem.

Here is the index controller:

def index
    @podcasts = Podcast.where.not(thumbnail_file_name: nil).reverse.last(5)
    @episodes = Episode.where.not(episode_thumbnail_file_name: nil).reverse.last(5)
end

Here is the routes file:

Rails.application.routes.draw do

  devise_for :podcasts

  resources :podcasts, only: [:index, :show] do
    resources :episodes
  end

  authenticated :podcast do
    root 'podcasts#dashboard', as: "authenticated_root"
  end

  root 'welcome#index'

end

Results of rake routes | grep episode:

podcast_episodes GET    /podcasts/:podcast_id/episodes(.:format)          episodes#index
                            POST   /podcasts/:podcast_id/episodes(.:format)          episodes#create
        new_podcast_episode GET    /podcasts/:podcast_id/episodes/new(.:format)      episodes#new
       edit_podcast_episode GET    /podcasts/:podcast_id/episodes/:id/edit(.:format) episodes#edit
            podcast_episode GET    /podcasts/:podcast_id/episodes/:id(.:format)      episodes#show
                            PATCH  /podcasts/:podcast_id/episodes/:id(.:format)      episodes#update
                            PUT    /podcasts/:podcast_id/episodes/:id(.:format)      episodes#update
                            DELETE /podcasts/:podcast_id/episodes/:id(.:format)      episodes#destroy

How can I correctly create a text link of the title using a link_to that links directly to the episode? Thanks!


Solution

  • When you're using link_to with a block, the only thing you need to pass into the block is the text of the link, so you should be able to do this (assuming your routes are setup properly):

    <% @episodes.each do |episode| %>
      <%= link_to episode, class="tt-case-title c-h5" do %>
        <%= episode.title %>
      <% end %>
    <% end %>
    

    UPDATE

    You really don't even need to use a block here. This should work fine for you and be a little more succinct.

    <% @episodes.each do |episode| %>
      <%= link_to episode.title, episode, class="tt-case-title c-h5" %>
    <% end %>
    

    UPDATE #2

    Thanks for including your route info. Try this:

    <% @episodes.each do |episode| %>
      <%= link_to episode.title, podcast_episode_path(episode.podcast, episode), class="tt-case-title c-h5" %>
    <% end %>