[英]Ruby on rails: How to update the view with a new query
我是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>
route.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>
我认为您可以阅读带有Active Record和路由的 查询
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.