1

從下拉列表索引頁排序深嵌套資源,讓我有三個型號:主題郵政段落。每個主題都有很多帖子,每個帖子都有很多段落。我需要實現的是按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,但我不能設法想出一個方法來連接主題PARAMS第一個帖子然後到段落。我根本不知道如何去做,而且似乎沒有太多的例子,所以任何想法都非常感謝。

回答

1

開始前,請檢查您是否在post.rb和topic.rb

OK指定accepts_nested_parameters_for ...,現在我們需要調整路由,使奇蹟發生。只需添加到routes.rb中:

patch 'paragraphs' => 'paragraphs#index' 
#we'll use PATCH for telling index which topic is active 

段#指數保持不變:

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 %> 

中提琴!

+0

這是現貨。謝謝! – Kasperi