1

所以我有三个模型:TopicPostParagraph。每个主题有很多帖子,每个帖子有很多段落。我需要实现的是按主题对段落进行排序paragraphs/index.html.erb

我当然有下拉菜单,包括所有主题:

<form>    
  <select>
    <% @topics.sort { |a,b| a.name <=> b.name }.each do |topic| %>
      <option><%= topic.name %></option>
    <% end %>
  </select>
 <input type="submit">
</form>

我遵循了以下建议:Filter results on index page from dropdown,但我无法想出一种方法将主题参数先连接到帖子,然后再连接到段落。我根本不知道如何使用它,而且似乎没有很多例子,所以任何想法都非常感谢。

4

1 回答 1

1

在开始之前,请检查您是否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 %>

中提琴!

于 2013-11-01T15:16:25.953 回答