簡體   English   中英

如何在我的 Rails 模型中訪問參數(或使用變通方法)?

[英]How can I access params (or utilize a workaround) in my rails model?

我正在嘗試將 Rails 控制器中的一些代碼重構為我的模型,但我發現我對 rails 工作原理的理解存在差距。 我試圖讓 Raffle 類可以使用這 2 種方法,但我正在努力理解如何做到這一點。 當我點擊此代碼時,返回錯誤“#Raffle:0x00007f88c9af8940 的未定義局部變量或方法`params'”。

如何解決模型無法使用的參數? 抱歉,如果這是一個初學者問題 - 我絕對是一個初學者。

#app/models/raffle.rb

class Raffle < ApplicationRecord
    has_many :tickets
    has_many :users, through: :tickets

    def bid_tickets(tier)
        params[:raffle][:"tier"].to_i #error returned here
    end
    
    def bid_total
        (bid_tickets(gold) * 3) + (bid_tickets(silver) * 2) + bid_tickets(bronze)
    end
#app/views/edit.html.erb

<%= form_for(@raffle) do |f| %>
  <%=f.label :ticket, "Gold" %>: <br>
  <%= image_tag "gold.jpg", class: "small_ticket" %><br>
  <%=f.number_field :gold%><br>
  <%=f.label :ticket, "Silver" %>:<br>
  <%= image_tag "silver.jpg", class: "small_ticket" %><br>
  <%=f.number_field :silver %><br>
  <%=f.label :ticket, "Bronze" %>:<br>
  <%= image_tag "bronze.jpg", class: "small_ticket" %><br>
  <%=f.number_field :bronze %> <br><br>
  <%= f.submit "Use Tickets" %>
<% end %><br>
#app/controllers/raffles_controller.rb

def update
      if @raffle.enough_slots? + @raffle.current_bids > @raffle.number_of_ticket_slots
              if enough_tickets? 
          redirect_to edit_raffle_path, notice: "You do not have enough tickets."
        else
        redirect_to edit_raffle_path, notice: "There aren't enough spots left in this raffle to handle your entry! Please use less tickets."
        end
      else @raffle.update_tickets(current_user)
        if @raffle.slots_filled?
          @raffle.select_winner
        end
       redirect_to edit_raffle_path(@raffle)
      end
    end
returned parameters:

{"_method"=>"patch",
 "authenticity_token"=>"xyz",
 "raffle"=>{"gold"=>"1", "silver"=>"", "bronze"=>""},
 "commit"=>"Use Tickets",
 "id"=>"1"}

編輯:

#app/controllers/raffles_controller.rb (StrongParameters)
class RafflesController < ApplicationController
 private 

    def raffle_params
      params.require(:raffle).permit(:product_name, :product_description, 
      :product_image, :number_of_ticket_slots, :filter)
    end
end

params在控制器中提供給你(通過 Rails),因為它是一個“網絡請求”。 最好不要將它更深入地傳遞到您的系統中,因為它包含外部“不受信任”的輸入。 這就是它在模型中不會自動可用的原因。

例如:

# controller
def update
  safe_value = validate_value(params[:unsafe_value]) # extract and validate

  # no "web request things" passed in
  result = MyFeature.do_stuff(@current_user, safe_value)  # pass it to other parts of system

  # then convert the result back into a "web request thing", e.g:
  # return render json: as_json(result)     # return result as json
  # return redirect_to endpoint_for(result) # redirect based on result
                                            # etc
end

在將數據作為參數傳遞給系統的其他部分(例如模型)之前,對參數進行預處理(提取值、驗證它們等)是一種很好的做法。

這將使系統的其余部分與“Web 請求事物”無關,使它們以目的為中心並且組織良好。

首先, StrongParameters是一個內置的 Rails 功能,可以幫助解決這個問題。

另一個建議是在使用參數的代碼中放置一個 binding.pry 或 byebug(在確保它已通過捆綁安裝和更新之后),然后運行您的代碼。 觸發類型參數后,您將看到細分。

暫無
暫無

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

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