![](/img/trans.png)
[英]Ruby on Rails - Lynda - Generating a Controller and View, Error on 'Rails Generate' Command
[英]Ruby On Rails Error 204 generate an image into a new view from controller
我的控制器中有一个创建自定义qr的方法
def generate_qrcode()
require 'rqrcode'
qrcode = RQRCode::QRCode.new('ejemplo')
image = qrcode.as_png(
resize_gte_to: false,
resize_exactly_to: false,
fill: 'white',
color: 'black',
size: 120,
border_modules: 4,
module_px_size: 6,
file: nil # path to write
)
return image.resize(150, 150)
end
在我的主视图中,我编辑一个li,以重定向到我的generate_qrcode()
index.html.erb
<p id="notice"><%= notice %></p>
<h1>Beneficios</h1>
<table>
<thead>
<tr>
<th>Id sucursal</th>
<th>Nombre</th>
<th>Estado</th>
<th>Descripcion</th>
<th>Tipo</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% @beneficios.each do |beneficio| %>
<tr>
<td><%= beneficio.Id_sucursal %></td>
<td><%= beneficio.Nombre %></td>
<td><%= beneficio.Estado %></td>
<td><%= beneficio.Descripcion %></td>
<td><%= beneficio.Tipo %></td>
<td><%= link_to 'Show', beneficio %></td>
<td><%= link_to 'Edit', edit_beneficio_path(beneficio) %></td>
<td><%= link_to 'Destroy', beneficio, method: :delete, data: { confirm: 'Are you sure?' } %></td>
<td><%= link_to 'Qr', :controller => :beneficios, :action => :generate_qrcode %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
<%= link_to 'New Beneficio', new_beneficio_path %>
在我的路线上
resources :beneficios do
collection do
get :generate_qrcode
end
end
但是,当我尝试生成qr时,我一直收到此错误消息
我在寻找答案,但找不到能帮助我解决这个问题的东西。
这是因为控制器期望您返回与动作名称相同的html模板。
您可以做的是创建一个与操作名称相同的新视图( views / generate_qrcode.html.erb )。
将二维码图像保存在实例变量中:
def generate_qrcode()
require 'rqrcode'
qrcode = RQRCode::QRCode.new('ejemplo')
image = qrcode.as_png(
resize_gte_to: false,
resize_exactly_to: false,
fill: 'white',
color: 'black',
size: 120,
border_modules: 4,
module_px_size: 6,
file: nil # path to write
)
@qr_code_img = image.resize(150, 150)
end
然后填充您创建的视图以显示二维码图像:
<%= image_tag @qr_code_img %>
要从控制器呈现原始二进制数据(例如图像),请使用send_data :
send_data(image.to_s, type: 'image/png', disposition: 'inline')
我建议以私有方法生成QR代码,然后从控制器操作中呈现该代码:
class BeneficiosController < ApplicationController
require 'rqrcode'
def generate_qrcode
qrcode = make_qrcode
send_data qrcode.to_s, type: 'image/png', disposition: 'inline'
end
private
def make_qrcode
qrcode = RQRCode::QRCode.new('ejemplo')
image = qrcode.as_png(
resize_gte_to: false,
resize_exactly_to: false,
fill: 'white',
color: 'black',
size: 120,
border_modules: 4,
module_px_size: 6,
file: nil # path to write
)
image.resize(150, 150)
end
end
您无法在控制器中返回图像对象以进行渲染。 您需要调用视图模板。 就您而言,您可以将您的qrcode或图像作为实例变量,然后将其传递到名为“ template_qrcode”的模板。
由于您要显示二维码,因此在模态窗口之类的弹出窗口中显示它可能比对用户重定向更方便,而不是将用户重定向到其他页面。 您可以在索引操作中生成所有qr代码模态,或使用Ajax按需生成它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.