首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails路由到资源

Rails路由到资源
EN

Stack Overflow用户
提问于 2016-07-09 20:20:17
回答 1查看 44关注 0票数 1

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

我让它来解决这个问题,尽管这显然不是这样做的方法:

代码语言:javascript
复制
<% @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被注释掉了,因为这是我问题的一部分。

以下是索引控制器:

代码语言:javascript
复制
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

以下是路由文件:

代码语言:javascript
复制
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结果

代码语言:javascript
复制
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正确地创建标题的文本链接?谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-07-09 20:27:22

当您使用带块的link_to时,唯一需要传递到该块的是链接的文本,因此您应该能够这样做(假设您的路由已经正确设置):

代码语言:javascript
复制
<% @episodes.each do |episode| %>
  <%= link_to episode, class="tt-case-title c-h5" do %>
    <%= episode.title %>
  <% end %>
<% end %>

更新

你真的不需要在这里用街区。这对你来说应该很好,而且更简洁一些。

代码语言:javascript
复制
<% @episodes.each do |episode| %>
  <%= link_to episode.title, episode, class="tt-case-title c-h5" %>
<% end %>

更新#2

谢谢你提供你的路线信息。试试这个:

代码语言:javascript
复制
<% @episodes.each do |episode| %>
  <%= link_to episode.title, podcast_episode_path(episode.podcast, episode), class="tt-case-title c-h5" %>
<% end %>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38286004

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档