Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?

There's probably a few ways to handle this, one off the top of my head would be to first add post_id to the Image model.

rails g migration addPostIdToImages post:references

which should give you

class AddPostToImages < ActiveRecord::Migration[5.2]
  def change
    add_reference :images, :post, foreign_key: true
  end
end

Then add your associations to your Post and Image models

class Post < ApplicationRecord
  has_many :images
end

class Image < ApplicationRecord
  belongs_to :post
end

Now you need to have the xhr request return the ID of each saved photo and load it into an array to be passed with the post attributes upon save. To do this, you need to first create a hidden field to hold the array of image_ids

app/views/posts/new.html.erb (you really should be using the _form.html.erb partial, but this is based on your repo)

<%=form_for @post do |form| %>
  ...
  <%= form.hidden_field :image_ids %>
  ...
<% end %>

then update trix_attachments.js to update the value of the hidden field on each upload

app/assets/javascripts/trix_attachments.js

xhr.onload = function() {
  if (this.status >= 200 && this.status < 300) {
    var data = JSON.parse(this.responseText);
                
    var image_ids_input = $("#post_image_ids");
    var image_ids = image_ids_input.val() ? JSON.parse(image_ids_input.val()) : []
    image_ids.push(data.image_id);
    image_ids_input.val(JSON.stringify(image_ids));

    return attachment.setAttributes({
      url: data.url,
      href: data.url,
    });
  }
};

In your post create action, you could take those ID's and assign them to the images

def create
  @post = Post.new(post_params)

  if @post.save
    image_ids = params['post']['image_ids']
    image_ids = image_ids.present? ? JSON.parse(image_ids) : nil
    if image_ids.present?
      Image.where(id: image_ids).update_all(post_id: @post.id)
    end

    redirect_to posts_path
  else
    render "new"
  end
end

Now you can get your images by its association with images, and since you want a random image, you can do

app/views/posts/index.html.erb

<% @posts.each do |post| %>
  ...
  <%= image_tag post.images.offset(rand(post.images.count)).first.image_url if post.images.present? %>
  ...
<% end %>

which will select one random image and display it if there are any attached images to that post.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.