我遇到了一个我不知道如何修复的问题。它与unsorted params hash有关。
我有一个对象预约,当我设置时间时,它具有虚拟时间=属性和虚拟的eating_session =属性=我也想通过外部服务器请求验证它。我在方法times()的帮助下做到这一点,该方法在其他服务器上进行查找并将所有可能的时间保存在@times变量中。
现在的问题是方法times()需要eating_session属性来找出哪些时间是有效的,但是rails我有时会先调用times =方法,然后在我只做@reservation时在Reservation对象中有任何eating_session = Reservation.new(params [:reservation])
class ReservationsController < ApplicationController
def new
@reservation = Reservation.new(params[:reservation])
# ...
end
end
class Reservation < ActiveRecord::Base
include SoapClient
attr_accessor :date, :time
belongs_to :eating_session
def time=(time)
@time = times.find { |t| t[:time] == time }
end
def times
return @times if defined? @times
@times = []
response = call_soap :search_availability {
# eating_session is sometimes nil
:session_id => eating_session.code, # <- HERE IS THE PROBLEM
:dining_date => date
}
response[:result].each do |result|
@times << {
:time => "#{DateTime.parse(result[:time]).strftime("%H:%M")}",
:correlation_data => result[:correlation_data]
}
end
@times
end
end
我不知道如何解决这个问题,任何帮助都是有帮助的。
答案 0 :(得分:0)
在这种情况下我经常做的是将依赖代码推送到验证中:
class ReservationsController < ApplicationController
def new
@reservation = Reservation.new(params[:reservation])
# ...
end
end
class Reservation < ActiveRecord::Base
include SoapClient
attr_accessor :date, :time
belongs_to :eating_session
validate :validate_time
def validate_time
errors.add_to_base "Time is invalid" unless @time = times.find { |t| t[:time] == time }
end
def times
return @times if defined? @times
@times = []
response = call_soap :search_availability {
# eating_session is sometimes nil
:session_id => eating_session.code, # <- HERE IS THE PROBLEM
:dining_date => date
}
response[:result].each do |result|
@times << {
:time => "#{DateTime.parse(result[:time]).strftime("%H:%M")}",
:correlation_data => result[:correlation_data]
}
end
@times
end
end