2012-11-22 35 views
1

我有一個優惠券制度,我試圖讓coupon對象與方法find_by「ArgumentError異常:未知鍵」與find_by

Coupon.find_by_coupon(params[:coupon]) 

我得到這個錯誤:

ArgumentError Exception: Unknown key: coupon 

我敢肯定params[:coupon]是正確的:

(rdb:1) eval params[:coupon] 
{"coupon"=>"100"} 

我有以下模型:

# Table name: coupons 
# 
# id    :integer   not null, primary key 
# coupon   :string(255) 
# user_id   :integer 

UPDATE:

它的工作,如果我把Coupon.find_by_coupon(params[:coupon][:coupon]),而不是Coupon.find_by_coupon(params[:coupon])

這裏跟在我看來,形式代碼:

<%= semantic_form_for Coupon.new, url: payment_summary_table_offers_path(@booking_request) do |f| %> 
    <%= f.input :coupon, :as => :string, :label => false, no_wrapper: true %> 
    <%= f.action :submit, :as => :button, :label => t(:button_use_coupon), no_wrapper: true, 
    button_html: { value: :reply, :disable_with => t(:text_please_wait) } %> 
<% end %> 
+0

這應該工作。你能發佈這個錯誤的完整堆棧跟蹤嗎? – tadman

+0

Oooh你有一個模型'Coupon'有一個名爲'coupon'的屬性嗎?嘗試重命名你的專欄'coupon_code' – MrYoshiji

+1

你是否嘗試直接設置值(100)。看看錯誤是否在別的地方? –

回答

2

如果您使用Rails 3,我建議你使用這個方法來找到對象:

# equivalent of find_all 
Coupon.where(:coupon => params[:coupon]) # => Returns an array of Coupons 
# equivalent of find :first 
Coupon.where(:coupon => params[:coupon]).first # => Returns a Coupon or nil 

嘗試做一個params.inspect看看究竟是如何做你的哈希。我認爲它是建立在這樣的:

{ :coupon => { :coupon => '100' } } 

如果是,你應該使用params[:coupon][:coupon]得到字符串「100」

按照您的更新:

semantic_form_for是創造形式你,當你給他一個Coupon.new它會建立這樣的參數:

params = { 
    :coupon => { :attribute_1 => 'value_1', :attribute_2 => 'value_2' } 
} 

如果你喜歡使用find_by方法:

Coupon.find_by_coupon(params[:coupon][:coupon]) # => Returns a Coupon or raise a RecordNotFound error 

或者與在其中方法:

Coupon.where(:coupon => params[:coupon][:coupon]).first # => Returns a Coupon or nil 
+0

爲什麼這樣做比find_by好? – bl0b

+1

http://stackoverflow.com/questions/9574659/rails-where-vs-find;) – MrYoshiji

+0

謝謝!由於表單當時只包含一張優惠券,因此我應該指定semantic_form_for只發送一張優惠券,而不是一組優惠券。 – bl0b