0

Im currently trying to convert my price_in_cents field to the virtual attribute of price_in_dollars. I did some research and basically implemented everything from the railscast virtual attributes video, here is the link below.

https://www.youtube.com/watch?v=Tr7tD2GPiXU

At first, the column in my db was 'amount' for the money field. So I ran a

$ rails g migration add_price_in_cents_to_payments price_in_cents:integer

then,

$ rake db:migrate

My application is just a basic CRUD scaffold for creating new payments.

I added the getter setter methods into the payment.rb file, like so.

 class Payment < ActiveRecord::Base
 attr_accessible :amount, :price_in_dollars, :from, :to
 # The price_in_dollars attribute is taking the place of :amount

 def price_in_dollars
   price_in_cents.to_d/100 if price_in_cents
 end

 def price_in_dollars=(dollars)
   self.price_in_cents = dollars.to_d*100 if dollars.present?
 end
end

And changed the form field to represent the new price_in_dollars attribute.

<div class="field">
  <%= f.label :price_in_dollars %><br />
  <%= f.text_field :price_in_dollars %>
</div>

But now when I submit a new payment, it returns the NoMethodError for my "new" and "create" methods in the payments controller. In the video, Bates does not even touch his controller. Here is my controller.

def new
    @payment = Payment.new

  respond_to do |format|
    format.html # new.html.erb
    format.json { render json: @payment }
  end
end

# GET /payments/1/edit
def edit
    @payment = Payment.find(params[:id])
end

# POST /payments
# POST /payments.json
def create
    @payment = Payment.new(params[:payment])

  respond_to do |format|
    if @payment.save
      format.html { redirect_to @payment, notice: 'Payment was successfully created.' }
      format.json { render json: @payment, status: :created, location: @payment }
    else
      format.html { render action: "new" }
      format.json { render json: @payment.errors, status: :unprocessable_entity }
    end
  end
end

Do I need to specify to pass in the (params[:price_in_dollars]) in all my CRUD methods in the controller? I'm a novice with only about 3 weeks of rails knowledge. Please help anyway possible.

bigREDcode
  • 159
  • 1
  • 3
  • 11

0 Answers0