如何在 Rails 的 Ruby 中检查 check_box 时添加价格

How to add price upon checking a check_box in Ruby on Rails

我在付费广告工作板上工作,并且正在使用 #Payola-Payments(Stripe 支付处理器 与 Rails 应用程序的实施) 对应用程序上的每项工作收取费用 post..

这是我喜欢做的事情:

When a check_box is checked, I want the price the application will deduct to change from default set price in my Jobs table, to the addition of the check_box worth.

我喜欢做的事的图解说明:

选中此框后,我的默认工作价格将增加 20 美元 table。

schema.rb

注意:在我的工作中设置了 200 美元的默认价格(即 20000)table。原因是 Payola 付款文档中的要求。因此,任何时候 post 的招聘广告,Stripe 都会从 his/her 信用卡中扣除 200 美元。

ActiveRecord::Schema.define(version: 20160827065822) do    
 create_table "jobs", force: :cascade do |t|
  t.string   "title",            limit: 255
  t.string   "category",         limit: 255
  t.string   "location",         limit: 255
  t.text     "description"
  t.text     "to_apply"
  t.datetime "created_at",                                   null: false
  t.datetime "updated_at",                                   null: false
  t.string   "name",             limit: 255
  t.integer  "price",                        default: 20000
  t.string   "permalink",        limit: 255
  t.string   "stripeEmail",      limit: 255
  t.string   "payola_sale_guid", limit: 255
  t.string   "email",            limit: 255
  t.string   "website",          limit: 255
  t.string   "company_name",     limit: 255
  t.boolean  "highlighted"
 end
end

我做了什么来解决这个问题:

我在模型 (job.rb) 中定义了一个名为 price_modification 的方法,并在其上调用了 before_save,这样我的模型看起来喜欢下面的代码 但没有用 :

class Job < ActiveRecord::Base

  include Payola::Sellable
  before_save :price_modification

  def price_modification
    price
  end

  def price_modification=(new_price)
    if :highlighted == t
      self.price += (price + 2000)
    else
      self.price = new_price
    end
  end

end

提前致谢。

正在使用 Ruby 2.2.4Rails 4.2.5.1

price_modification 是一种不做任何更改的访问器方法。

before_save :price_modification 正在调用 price_modification 方法,该方法仅 returns price 值但未进行任何更改。

我不确定你在找什么,但我最好的猜测是这样的:

class Job < ActiveRecord::Base
  ...

  # Use before_create instead of before_save so
  # apply_extra_fees is *not* called multiple times.
  before_create :apply_extra_fees

  HIGHLIGHT_FEE_IN_CENTS = 2000

  def apply_extra_fees
    if highlighted?
      self.price += HIGHLIGHT_FEE_IN_CENTS
    end
  end

  ...
end