Ask A Question

Notifications

You’re not receiving notifications from this thread.

How do I save a save a has_many association?

Morgan asked in Rails

I have setup a service that parses and saves the result of an external API which all works great, however, I can't work out how to save the array of images that need to be saved in a has_many relation.

The service:

module Domain
  class FetchUserPosts

    def initialize(token)
      @token = token
    end

    def get_listings
      resp = client.get("/v1/some/api/posts")

      resp.body.each do |post|
       @user.posts.create(
          headline: post["headline"],
          body: post["body"],
          images: listing["media"].map { |l| l["url"]} ???
        )
      end
    end

    private

    def client
      Faraday.new(url: "https://example.com", headers: { "Authorization" =>  "Bearer #{@token}" }) do |f|
        f.request :json
        f.request :retry
        f.response :logger, Rails.logger
        f.response :raise_error
        f.response :json
        f.adapter Faraday.default_adapter
      end
    end

  end
end

The Post Model that it saves to:

class Post < ApplicationRecord
  belongs_to :user
  has_many :images, as: :imageable
end

And the associated Image model:

class Image < ApplicationRecord
  belongs_to :imageable, polymorphic: true
end

Everything works except I'm unsure how to deal with the images which look like:

[{
   "type" => "image",
   "url" => "https://image-1.jpg"
 }, {
   "type" => "image",
   "url" => "https://image-2.jpg"
}]
Reply

Hey Morgan,

Just iterate through the images and save each one like you would any has_many

def get_listings
  resp = client.get("/v1/some/api/posts")

  resp.body.each do |post|
    user = @user.posts.new(
      headline: post["headline"],
      body: post["body"]
    )

    listing["media"].each do |media|
      user.images.build(url: media["url"])
    end

    user.save
  end
end

I haven't tested this, so you may have to play around with it some (you may need to actually save the user first, then iterate through and build the associations, I can't recall off the top of my head) but you should get the idea.

Reply

Thanks Jacob!

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 81,842+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more.

    © 2024 GoRails, LLC. All rights reserved.