开发者

Using a method while looping through an array in ruby

开发者 https://www.devze.com 2023-01-24 20:46 出处:网络
I am using ruby-aaws to return Amazon Products and I want to enter them into my DB. I have created a model Amazonproduct and I have created a method get_amazon_data to return an array with all the pro

I am using ruby-aaws to return Amazon Products and I want to enter them into my DB. I have created a model Amazonproduct and I have created a method get_amazon_data to return an array with all the product information. When i define the specific element in the array ( e.g. to_a[0] ) and then use ruby-aaws item_attributes method, it returns the name I am searching for and saves it to my DB. I am trying to iterate through the array and still have the item_attributes method work. When i don't define the element, i get this error: undefined method `item_attributes' for #Array:0x7f012cae2d68

Here is the code in my controller.

def create
@arr = Amazonprod开发者_C百科uct.get_amazon_data( :r ).to_a
 @arr.each { |name|
   @amazonproduct = Amazonproduct.new(params[:amazonproducts])
   @amazonproduct.name = @arr.item_attributes.title.to_s
 }

EDIT: Code in my model to see if that helps:

class Amazonproduct < ActiveRecord::Base

  def self.get_amazon_data(r)
   resp = Amazon::AWS.item_search('GourmetFood', { 'Keywords' => 'Coffee Maker' })
   items = resp.item_search_response.items.item
   end
end

Thanks for any help/advice.


I'm not familiar with the Amazon API, but I do observe that @arr is an array. Arrays do not usually have methods like item_attributes, so you probably lost track of which object was which somewhere in the coding process. It happens ;)

Try moving that .item_attributes call onto the object that supports that method. Maybe amazonproduct.get_amazon_data(:r), before its being turned into an array with to_a, has that method?


It's not quite clear to me what your classes are doing but to use #each, you can do something like

hash = {}

[['name', 'Macbook'], ['price', 1000]].each do |sub_array|
  hash[sub_array[0]] = sub_array[1]
end

which gives you a hash like

{ 'name' => 'Macbook', 'price' => 1000 }

This hash may be easier to work with

@product = Product.new
@product.name = hash[:name]
....

EDIT

Try

def create
  @arr = Amazonproduct.get_amazon_data( :r ).to_a
  @arr.each do |aws_object|
    @amazonproduct = Amazonproduct.new(params[:amazonproducts])
    @amazonproduct.name = aws_object.item_attributes.title.to_s
  end
end
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号