在开始之前,请检查您是否accepts_nested_parameters_for ...
在 post.rb 和 topic.rb 中指定
好的,现在我们需要调整路由以使魔术发生。只需添加到 routes.rb:
patch 'paragraphs' => 'paragraphs#index'
#we'll use PATCH for telling index which topic is active
Paragraphs#index 保持不变:
def index
@topics = Topic.all
end
其余的我们将在视图中完成。所以,index.html.erb:
<h1>Listing paragraphs sorted by Topic</h1>
<% names_options = options_from_collection_for_select(@topics, :id, :name, selected: params[:topic_id]) %>
<%= form_tag({action: "index"}, method: "patch") do %>
<%= select_tag :topic_id, names_options,
{prompt: 'Pick a topic', include_blank: false} %>
<%= submit_tag "Choose" %>
<% end %>
<% @topics = @topics.where(:id => params[:topic_id]).includes(:posts => :paragraphs) %>
<% @topics.each do |topic| %>
<option><%= topic.name %></option>
<h2><%= topic.name %></h2>
<% topic.posts.each do |post| %>
<h3><%= post.content %></h3>
<% post.paragraphs.each do |paragraph| %>
<%= paragraph.content %><br>
<% end %>
<% end %>
<% end %>
中提琴!