0

我目前正在尝试将我的 price_in_cents 字段转换为 price_in_dollars 的虚拟属性。我做了一些研究,基本上实现了 railscast 虚拟属性视频中的所有内容,这是下面的链接。

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

起初,我的数据库中的列是货币字段的“金额”。所以我跑了一个

$ rails g migration add_price_in_cents_to_payments price_in_cents:integer

然后,

$ rake db:migrate

我的应用程序只是用于创建新支付的基本 CRUD 脚手架。

我将 getter setter 方法添加到payment.rb文件中,就像这样。

 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

并更改了表单字段以表示新的 price_in_dollars 属性。

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

但是现在当我提交新的付款时,它会在付款控制器中为我的“new”和“create”方法返回 NoMethodError。在视频中,贝茨甚至没有触摸他的控制器。这是我的控制器。

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

我是否需要指定(params[:price_in_dollars])在控制器中传入我的所有 CRUD 方法?我是一个新手,只有大约 3 周的 Rails 知识。无论如何请帮助。

4

0 回答 0