作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我是 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 Record和 routing
关于mysql - Ruby on Rails : How to update the view with a new query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40493097/
我是一名优秀的程序员,十分优秀!