gpt4 book ai didi

mysql - Ruby on Rails : How to update the view with a new query

转载 作者:行者123 更新时间:2023-11-29 20:02:05 25 4
gpt4 key购买 nike

我是 Ruby on Rails 的新手(我这周开始自学),我面临着一些无法解决的问题。

我创建了一个名为“projeto_ajuda”的项目,并且正在使用 mysql 数据库。我访问 http://localhost:3000/menu/index 上的应用程序。它向我展示了一个有 5 列的表格,最后一个是用于按钮的。我想要的是:当单击按钮时,它会调用 Controller 中的一个方法,该方法使用新的选择“刷新”表(我在 where 语句中添加一个新条件)。

Ps1: View 显示表中的填充行,但是当我单击按钮时, View 上没有任何变化,但 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

最佳答案

试试这个

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

关于mysql - Ruby on Rails : How to update the view with a new query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40493097/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com