[英]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.