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?

1 Answer 1

2

Instead of Image.create, use Image.new or @page.images.build:

@output["images"].each do |image_data|
  image = @page.images.build image_data
  //...  manipulate as needed
  image.save
end
Sign up to request clarification or add additional context in comments.

2 Comments

What about using before_create to manipulate the data? For manipulation I basically need to do some calculations among some attributes to fill the value of another attribute.
@HommerSmith: You could do that, although model callbacks are typically intended to be used to ensure data integrity. If this is a business concern, it may be more wise to separate it out to a component that handles this, allowing you to swap it out if needed. That said, a callback will certainly work just fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.