我有两个相关的模型 - Tour&保留。 Tour具有“amount”属性。我正在使用复选框来确定是否根据用户输入(复选框)更改金额。默认值设置为false。
目标:
我希望@tour.amount仅在选中任一复选框时进行更改。我有以下内容,但无论是否选中复选框,它都会收取额外的金额。我错过了什么?我尝试将参数比较为0,“0”,但无效。
if @reservation.update_attribute(:option1, params[:option1]) == true || @reservation.update_attribute(:option2, params[:option2]) == true
@tour.amount = @tour.amount + 1500
else
@tour.amount = @tour.amount
end
PARAMS:
Params (unchecked)
"option 1"=>"0", "option 2"=>"0"
Params (checked)
"option 1"=>"0", "option 2"=>"0"
控制器:
def new
@reservation = Reservation.new
@tour = Tour.find(params[:tour_id])
end
def create
@tour = Tour.find(params[:tour_id])
@reservation = Reservation.new(reservation_params)
if @reservation.update_attribute(:option1, params[:option1]) == true || @reservation.update_attribute(:option2, params[:option2]) == true
@tour.amount = @tour.amount + 1500
else
@tour.amount = @tour.amount
end
if @reservation.save
Stripe::Charge.create(
:amount => @tour.amount, # amount in cents, again
:currency => "usd",
:card => params[:stripeToken]
)
flash[:success] = "Your reservation has been booked for #{@reservation.passengers} person(s). Please save this info."
redirect_to new_tour_reservation_path(@tour)
else
render 'new'
end
end
解: (不要过分思考!)
if @reservation.option1 == true && @reservation.option2 == true
@tour.amount = @tour.amount + 3000
elsif @reservation.option1 == true
@tour.amount = @tour.amount + 1500
elsif @reservation.option2 == true
@tour.amount = @tour.amount + 1500
else
@tour.amount = @tour.amount
end
答案 0 :(得分:1)
如果param为true或false,则检查update_attribute调用是否成功。