首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails -在添加到新对象之前如何检查是否已定义?

Rails -在添加到新对象之前如何检查是否已定义?
EN

Stack Overflow用户
提问于 2013-08-28 00:20:40
回答 1查看 41关注 0票数 0

我正在使用Amazon产品广告API,我正在我的控制器中调整它的响应,以呈现定制的JSON,但是它的响应根据产品类别的不同而有很大变化,所以我需要编写代码来捕捉它变化的所有方式。我只需要几个数据,所以在我自己的自定义JSON中包含这些数据之前,我如何简单地检查这些片段是否存在于Amazon的API响应中?

注意:我使用这块宝石与亚马逊的API集成。它在自己的对象中返回API响应。

代码语言:javascript
复制
@results = (Amazon's API response)
@custom_response = []
@results.items.each do |product|
        @new_response = OpenStruct.new(
                        :id => product.asin, 
                        :source => "amazon", 
                        :title => product.title, 
                        :price => @product_price, 
                        :img_small => @images[0], 
                        :img_big => @images[1], 
                        :category =>  product.product_group, 
                        :link => "http://amazon.com/" )
        @custom_response << @new_response
end
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-08-28 00:34:32

你可以这样做:-

代码语言:javascript
复制
@new_response = OpenStruct.new(:source => "amazon", :link => ".....")

@new_response.id = product.asin if product.asin.present? 
@new_response.title = product.title if product.title.present?
other attributes....             
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18477486

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档