我在以下代码中收到错误消息: PurchasesesController中的NameError #create 未初始化的常量Purchase :: PurchaseCodeID
purchase_controller.rb
:
class PurchasesController < ApplicationController
def create
#if @memberTier = PurchaseCode.find_by(Code: 123456).Code then
@purchase=Purchase.create(purchase_params)
redirect_to :back
#end
end
def index
@purchases = Purchase.where(UserID: current_user.id)
@sum = Purchase.where(UserID: current_user.id).sum(:Points)
@redemp = Redemption.where(UserID: current_user.id).sum(:RedemptionID)
@deff = RedemptionDetail.where(RedemptionID: @redemp).sum(:Points)
@ans = @sum - @deff
end
def new
@purchase = Purchase.new(purchase_params)
end
def purchase_params
params.require(:purchase).permit(:PurchaseID,:PurchaseCodeID,:Points, :UserID)
end
end
purchase.rb
:
class Purchase < ActiveRecord::Base
validates :PurchaseCodeID, presence: true,
length: { minimum: 5 }
def self.create(purchase_params)
begin
@purchaseid = Purchase.last.id
@purchaseid = @purchaseid + 1
rescue
@purchaseid = 1
end
@code = PurchaseCode.find_by(Code: PurchaseCodeID).Code
@purchase = Purchase.new(purchase_params)
@purchase.PurchaseCodeID = @code
@purchase.PurchaseID = @purchaseid
@purchase.UserID = User.current.id
@userTier = User.current.TierID
@tierPoint = MembershipTier.find_by(TierID: @userTier).RequiredPoint
@purchase.Points = @tierPoint
@purchase.save
end
end
view/purchases/index.html.erb
:
<h1>Purchase History</h1>
<p>
Enter the code here:</br>
<%= form_for :purchase, url: purchases_path do |f| %>
<p>
<%= f.text_field :PurchaseCodeID %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
<table>
<thead>
<tr>
<th>Points</th>
<th>Date</th>
<th>Time</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% @purchases.each do |purchase| %>
<tr>
<td><%= purchase.Points %></td>
<td>|<%= purchase.created_at.to_s.to_date.strftime("%e %B, %Y") %></td>
<td><%= purchase.created_at.to_s.to_time.strftime("| %I:%M %P") %></td>
</tr>
<% end %>
</tbody>
</table>
<tr>
<td><p>Current Points: <%= @ans %></p></td>
</tr>
<%= link_to t('sign_out'), destroy_user_session_path, method: :delete %>
我正在使用rails 4.希望有人能帮我解决问题。谢谢。
答案 0 :(得分:1)
PurchaseCodeID
似乎位于purchase_params
,因此您应该更改此行:
@code = PurchaseCode.find_by(Code: PurchaseCodeID).Code
为:
@code = PurchaseCode.find_by(Code: purchase_params[:PurchaseCodeID]).Code