Rails路由到资源

时间:2016-07-09 20:20:18

标签: ruby-on-rails routes link-to

我正在构建一个播客目录的Rails应用。我有播客和剧集。 Episode属于Podcast,而Podcast有很多剧集。在主页上,我想显示已创建的最后5集并链接到它们。

我有这个工作,虽然这显然不是这样做的方法:

<% @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 %>

link_to已被注释掉,因为这是我问题的一部分。

这是索引控制器:

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

这是路线文件:

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

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

如何使用直接链接到剧集的link_to正确创建标题的文本链接?谢谢!

1 个答案:

答案 0 :(得分:0)

当你使用link_to一个块时,你需要传递给块的唯一内容是链接的文本,所以你应该能够这样做(假设您的路由设置正确) :

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

更新

你真的甚至不需要在这里使用一个块。这应该对你有用,并且更简洁。

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

更新#2

感谢您提供路线信息。试试这个:

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