2

I have a controller which is used to parse a site. From that parsing, I get a JSON object. In that JSON object I have mainly two things: prices and images.

So, a Page has many Price and Image. First thing I do when creating the controller is:

@page = Page.create(:url => parsed_url)

Then from the @output, I want to be able to create several @images and @prices. So, I do this:

@prices = @output["prices"]
@images = @output["images"]

So, @images look like [{:width => 12, :height => 13, :src => 'http...'}, {:width => 20,..}]

I want to create an Image associated with that @page for each object in the array. Before doing that though I might need to check those attributes (width, height) and manipulate them before inserting them to the DB. So my question is... Where and how should I do this?

I know how to create an Image by doing Image.create(:page_id => @page.id, :width => 12...), but how do I do that form that JSON response that needs to be treated first?

4

1 回答 1

2

代替Image.create, 使用Image.new@page.images.build:

@output["images"].each do |image_data|
  image = @page.images.build image_data
  //...  manipulate as needed
  image.save
end
于 2013-11-07T18:41:19.337 回答