我正在构建一个播客目录的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正确创建标题的文本链接?谢谢!
答案 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 %>
感谢您提供路线信息。试试这个:
<% @episodes.each do |episode| %>
<%= link_to episode.title, podcast_episode_path(episode.podcast, episode), class="tt-case-title c-h5" %>
<% end %>