簡體   English   中英

使用 link_to 更新 rails 6 參數

[英]Updating rails 6 params with a link_to

您好,我有一個屬於企業的發票列表,並且該企業也屬於用戶,我試圖在表格上設置一個按鈕(鏈接到),其中列出了所有發票,以便用戶能夠更新發票的狀態。 幾乎如果用戶點擊鏈接,它將從付費:true 變為付費:false 和 viseversa。 以下是路線:

  resources :businesses do
    resources :invoices
  end

以下是鏈接所在的表格部分:

<% if invoice.paid %>
   <td><%= link_to "Mark as Not Paid", business_invoice_path(current_user, invoice), method: 'put', data: {paid: false} %></td>
<% else %>
   <td><%= link_to "Mark as Paid", business_invoice_path(current_user, invoice), method: 'put', data: {paid: true}%></td>
<% end %>

注意:付費欄是數據庫上的 boolean

由於發票上存在已付費列,因此如果您在 controller 或 model 級別處理它,而不是從表單中獲取值,效果會更好。

刪除 if else 條件並將其組合如下:

<%
  invoice_text = invoice.paid ? 'Mark as Not Paid' : 'Mark as Paid'
%>
<td><%= link_to invoice_text, business_invoice_path(invoice), method: :put %></td>

Business::InvoicesController中,您可以像這樣在update中編寫邏輯:

Business::InvoicesController < ApplicationController
  before_action :authenticate_user!
  before_action :set_invoice

  def update
    # TODO: find the business using the invoice
    # have a check in place to authorize the 
    # transaction (if invoice belongs a business which 
    # belongs the current_user or not, if not then raise Unauthorized error)
    # if business does belongs to the current_user then proceed to next step

    # invert the value of paid column based on existing value
    @invoice.update(paid: !@invoice.paid)
  end

  private

  def set_invoice
    @invoice = Invoice.find(params[:id])
  end
end

使用上述邏輯,您可以忘記維護/查找paid 列的值,因為您可以選擇將paid 的值恢復為true並恢復為false 另外,我假設您使用 Devise 進行身份驗證。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM