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

96 Views Asked by At

I am working on a paid ad job board, and am using #Payola-Payments (Implementation of Stripe Payment Processor with Rails Application) to charge each job post on the app..

This is what I like to do:

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.

Pictorial explanation of what I like to do:

Upon checking the box, it's suppose to add $20 to my default price in jobs table.

My Job Post Form

schema.rb

Note: A price default of $200 in cents (i.e. 20000) is set in my jobs table. The reason being what is required in Payola-payments documentation. So anytime anyone posts job advert, $200 will be deducted from his/her credit card by Stripe.

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

What I have done to solve this:

I defined a method inside my model (job.rb) called price_modification and called before_save on it, such that my model looks like this code below but didn't work:

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

Thanks in advance.

Am using Ruby 2.2.4 and Rails 4.2.5.1

1

There are 1 best solutions below

2
On BEST ANSWER

price_modification is an accessor method that makes no changes.

The before_save :price_modification is calling the price_modification method which only returns the price value but makes no changes.

I'm not certain what you're looking for but my best guess is something like this:

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