2016-11-08 59 views
0

我是Ruby on Rails的新手(我自己在本週開始學習),並且遇到了一些我無法解決的問題。Ruby on rails:如何使用新查詢更新視圖

我創建了一個名爲'projeto_ajuda'的項目,我使用的是mysql數據庫。我訪問http://localhost:3000/menu/index上的應用程序。它向我展示了一個5列的表格,最後一個表格是一個按鈕。 我想要的是:單擊按鈕時,它會從控制器調用一個方法,使用新選擇(我在where語句中添加一個新條件)刷新表。

Ps¹:視圖顯示在桌上擺滿行,但是當我按一下按鈕,就沒什麼看法改變了,但URL的作用:http://localhost:3000/menu/index.%23%3CMenu::ActiveRecord_Relation:0x007f5ce5891608%3E?id=6

Ps²:如果我refresh_table(6)代替refresh_table(nil)在索引方法上,它工作得很好,從數據庫中選擇我想要的。

如果我看的數據庫中,有id爲創紀錄的6

menu_controller.rb:

class MenuController < ApplicationController 
    helper :all 

    def index 
    refresh_table(nil) 
    end 

    def abrir 
     refresh_table(params[:id]) 
    end 

    private 
    def refresh_table(id) 

     if(id.nil?) 
      @menus = Menu.where("codigopai IS NULL") 
     else 
      @teste = Menu.find(id) 
      @menus = Menu.where("codigopai = '" + @teste.codigopai.to_s + @teste.codigo.to_s + "'") 
     end 
    end 

end 

index.html.erb:

<h1> List all </h1> 

<table> 
    <tr> 
    <th>Codigo</th> 
    <th>CodigoPai</th> 
    <th>Descrição</th> 
    <th>Conteúdo</th> 
    <th></th> 
    </tr> 
    <% @menus.each do |m| %> 
    <tr> 
     <td><%= m.codigo %></td> 
     <td><%= m.codigopai %></td> 
     <td><%= m.descricao %></td> 
     <td><%= m.conteudo %></td> 
     <td><%= button_to 'Abrir', menu_index_path(@menus, :id => m.id), method: :post %></td> 
    </tr> 
    <% end %> 
</table> 

路線.rb:

Rails.application.routes.draw do 
    resources :menus 

    post 'menu/index' 
    get 'menu/index' 

    # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html 
end 

回答

0

試試這個

menu_controller.rb

class MenuController < ApplicationController 
    helper :all 

    def index 
    refresh_table(params[:id]) 
    end 

    private 
    def refresh_table(id) 
     if id 
     @teste = Menu.find(id) 
     @menus = Menu.where(codigopai: "#{@teste.codigopai}#{@teste.codigo}") 
     else 
     @menus = Menu.where(codigopai: nil) 
     end 
    end 
end 

index.html.erb

<h1> List all </h1> 

<table> 
    <tr> 
    <th>Codigo</th> 
    <th>CodigoPai</th> 
    <th>Descrição</th> 
    <th>Conteúdo</th> 
    <th></th> 
    </tr> 
    <% @menus.each do |m| %> 
    <tr> 
     <td><%= m.codigo %></td> 
     <td><%= m.codigopai %></td> 
     <td><%= m.descricao %></td> 
     <td><%= m.conteudo %></td> 
     <td><%= button_to 'Abrir', menu_index_path(id: m.id), method: :post %></td> 
    </tr> 
    <% end %> 
</table> 

我覺得你可以閱讀Query with Active Recordrouting

+0

它的工作就好了。我試圖閱讀這些文章,但我不確定我是否理解正確。不過謝謝你! –