在rails中向API传递实例变量



我试图传递一些实例变量来调用具有该特定对象属性的API。用户填写他们的汽车详细信息(品牌、型号和年份),从而创建一个offer对象。这应该被传递到埃德蒙的API来检索那辆车的信息。如果我将其设置为特定的品牌/型号/年份,则代码可以正常工作,但我无法使其返回创建的报价对象的信息。

这是我的控制器:

def show
@offer = Offer.find(params[:id])
@wanted_ad = WantedAd.find(params[:wanted_ad_id])
@make = @offer.ownermake
@model = @offer.ownermodel
@year = @offer.owneryear
respond_to do |format|
  format.html # show.html.erb
  format.json { render json: @offer }
end
end

这是我的模型:

class Offer < ActiveRecord::Base
    attr_accessible :user_id, :wanted_ad_id, :estvalue, :image1, :offerprice, :ownercartype, :ownerdesc, :ownermake, :ownermileage, :ownermodel, :owneryear
    belongs_to :user
    belongs_to :wanted_ad
    has_one :car
    def self.carsearch
        @car = []

        carinfo = HTTParty.get("http://api.edmunds.com/v1/api/vehicle/#{make}/#{model}/#{year}?api_key=qd4n48eua7r2e59hbdte5xd6&fmt=json")
        carinfo["modelYearHolder"].each do |p|
            c = Car.new
            c.make = p["makeName"]

            return carinfo
    end 
    end
end

我的汽车模型很简单:

class Car < ActiveRecord::Base   
  attr_accessible :make, :model, :year 
  belongs_to :offer  
end

我试图从<%= Offer.carsearch %>的视图文件中调用它。我可能搞砸了,但这是我第一次使用API,我很迷茫。

我认为你在carsearch方法中有几个逻辑错误:您正在获取carinfo,遍历数组,实例化一辆新车,但c对象没有发生任何变化,并且在第一次迭代结束时,您退出整个函数,返回检索到的carinfo

这可能是你的意思吗?

def carsearch
    @cars = []
    # where do `make`, `model` and `year` come from here?
    # probably method parameters!?
    carinfo = HTTParty.get("http://api.edmunds.com/v1/api/vehicle/#{make}/#{model}/#{year}?api_key=qd4n48eua7r2e59hbdte5xd6&fmt=json")
    carinfo["modelYearHolder"].each do |p|
        c = Car.new
        c.make = p["makeName"]
        # initialize other attributes (year, model)?
        @cars << c
    end

    return @cars
end

最新更新