【问题标题】:Rails route to a resourceRails 路由到资源
【发布时间】:2016-11-12 03:57:08
【问题描述】:

我正在构建一个作为播客目录的 Rails 应用程序。我有播客和剧集。 Episode 属于 Podcast,Podcast 有很多 Episode。在主页上,我想显示最近创建的 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 正确创建标题的文本链接?谢谢!

【问题讨论】:

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


    【解决方案1】:

    当您将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 %>
    

    【讨论】:

    • 谢谢。我收到以下错误:未定义的方法“episode_path”。我已更新问题以包括路线。
    • @R.Coy 您可以将此命令的输出添加到您的问题中吗? - rake routes | grep episode
    • @R.Coy 您将在终端窗口中运行该 ^ 命令(以防万一您不知道)。 :-)
    • 我已将结果添加到上述问题中。谢谢。
    • 明白了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多