Evelyn St Evelyn St - 25 days ago 10
Ruby Question

Ruby on rails: How to update the view with a new query

I'm new at Ruby on Rails (I started studying this week by myself) and I'm facing some issues that I cannot solve.

I have created a project called 'projeto_ajuda' and i'm using mysql database. I access the aplication on http://localhost:3000/menu/index. It shows me a table with 5 columns, and the last one, is for a button.
What I want is: when the button is clicked, it calls a method from the controller that 'refresh' the table with a new select (i add a new condition in where statement).

Ps¹: the view show to filled rows in the table, but when I click on the button, nothing changes on the view, but the URL does: http://localhost:3000/menu/index.%23%3CMenu::ActiveRecord_Relation:0x007f5ce5891608%3E?id=6

Ps²: If I refresh_table(6) instead of refresh_table(nil) on the index method, it works just fine, selecting what I want from the database.

And if I look at the database, there is a record with the 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>


routes.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

Answer

Try this

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>

I think you can read Query with Active Record and routing

Comments