在create action中检查API(没有保存数据)

时间:2014-08-14 03:51:07

标签: ruby-on-rails ruby-on-rails-3

我想在用户创建记录时对Web API进行检查。有办法吗?另一种方法是创建一个从创建操作重定向的新操作,但我想避免这种情况。

控制器代码

  def create
   @reload = Reload.new(params[:reload])
   time = Time.now
   complete_date = time.strftime("%d%m%y%H%M%S")
   reload_count = Reload.all.count
   reload_count_id = reload_count.to_s.rjust(5, '0')
   generated_reference_id = complete_date + reload_count_id
   @reload.reference_id = 'R'+generated_reference_id

   template = Addressable::Template.new("http://host.mydomain.com/remote_api.php{?query*}")
   url = template.expand({ 'query' => { 'msisdn' => '6#{@reload.number}', 'type' => 'json' } })
   csgdata = JSON.load(open(url))
   isregistered = csgdata['IsRegistered']

   if (isregistered == TRUE)
       flash[:notice] = "It is working!"
   end

   if user_signed_in?
     @reload.user_id = current_user.id
     @reload.guest = false
   else
     @reload.guest = true
   end
   respond_to do |format|
     if @reload.save
        format.html { redirect_to checkout_reload_path(@reload) }
     else
        format.html { render action: "new" }
        format.json { render json: @reload.errors, status: :unprocessable_entity }
     end
   end
  end

上面的代码实现了rest_client和addressable gem,试图从API中检查输入到系统中的数字是否可用。

2 个答案:

答案 0 :(得分:1)

在模型中,使用回调 after_create

Class Bar < ActiveRecord::Base
after_create :foo

  def foo
    # here you can check whatever you want after the object was really 
    # created (only at the first time then. If you want to check every 
    # time after the object is saved, then use #after_save)
  end

答案 1 :(得分:-1)

需要“可寻址/模板”

def create
 @reload = Reload.new(params[:reload])

 template = Addressable::Template.new("http://localhost.localdomain/remote.php{?query*}")
  url = template.expand({ 'query' => { 'msisdn' => "6#{@reload.number}", 'type' => 'json' } })
  data = JSON.load(open(url))

  isregistered = data['IsRegistered']
  terminateddate = data['TerminatedDate']
  firstcalldate = data['FirstCallDate']
  onpeakaccountidexpiry = data['OnPeakAccountIDExpiryDate']

  if (isregistered == 'TRUE' && terminateddate != nil && firstcalldate != nil)
    if (onpeakaccountidexpiry > Time.now.to_s(:db))
     respond_to do |format|
       if @reload.save
         format.html { redirect_to checkout_reload_path(@reload) }
       else
         format.html { render action: "new" }
         format.json { render json: @reload.errors, status: :unprocessable_entity }
       end
     end
    else
       redirect_to new_reload_path, flash: { error: "Your account is not active" }
       # flash[:error] = "Account is not active"
    end
  else
       redirect_to new_reload_path, flash: { error: "Your account is not registered" }
       # flash[:error] = "Your account is not registered"
  end
end