2016-11-08 7 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

私はあなたはそれがうまく働いたQuery with Active Recordrouting

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

を試してみてください。私はこれらの記事を読もうとしましたが、私が正しく理解しているかどうかはわかりません。とにかくありがとう! –

関連する問題