简体   繁体   中英

How to attach an image from assets to a ruby object in rails 5

I'm trying to build a chess game, and I currently have the pieces being initialized through the game model, as so:

    class Game < ApplicationRecord
  scope :available, -> { where(white_player_id: nil).or(where(black_player_id: nil))}
  belongs_to :user
  has_many :pieces
  after_create :populate_game


  def populate_game
    #black pieces 

    (0..7).each do |i|
      Pawn.create(game_id: id, x_position: i, y_position: 6, color: "black", status: true, image: 'pwn_blk.png')
    end 

the rest of the pieces are built the same way, but for sake of space I don't have those included.

My issue is, the image that represents the pieces is giving me trouble. I have the board being built out in javascript, one square at a time, and I am appending a span to the square that corresponds with the correct piece. I can get the piece id's to work great, but when I am trying to reference the image stored in the model (whether I am using span.setAttribute('img', "src=${piece.image}") or appending a seperate child to the span, or an entirely different child to the containing square) I receive an error in the console saying GET http://localhost:3030/games/assets/images/pwn_blk.png 404 (Not Found) so it is as if the application is trying to reach the image from a url endpoint rather than just pulling from the assets folder.

My one thought as to why this may be is this, we have the pieces being built out as a JSON endpoint and being retreived with an ajax request, as follows:

function getGamePieces(id) {
     $.ajax({
        url: `/get_pieces/${id}`,
        method: 'get',

     }).then(function (data) {
       let pieces = data; 
       // console.log(pieces);
       pieces.forEach(function (piece) {
        var row = $boardContainer.querySelector(`[data-x="${piece.x_position}"][data-y="${piece.y_position}"]`);


         if (row){
          var image = document.createElement('img');
          image.setAttribute('src', `./assets/images/pwn_blk.png`); 
          var span = document.createElement('span');
          span.className = 'piece';
          span.setAttribute('draggable', 'true')
          span.setAttribute('ondragstart', 'onDragStart(event);')
          span.setAttribute('id', piece.id);
          span.setAttribute('img', `src=${piece.image}`);
          // span.append(piece.image);
          row.appendChild(span);
         }
       })

     })    
}        

It's a tad messy right now because I have been experimenting a lot trying to figure out how to make it work and I'm coming up short. Any suggestions on how to get the image to pull directly from the assets folder?

You should use image_path to get the path of the image in the assets. https://api.rubyonrails.org/v5.2.0/classes/ActionView/Helpers/AssetUrlHelper.html#method-i-image_path

Then use a data attribute on your element to set the image url, so you can retrieve it later with JavaScript.

The issue was with image fingerprinting in rails, only the hard-coded image names would be fingerprinted when compiling, and not names given as a variable or called using piece.image. I used https://github.com/alexspeller/non-stupid-digest-assets in order to remove the necessity for pieces to be fingerprinted, and adjusted the filepath to the images to look like span.innerHTML = ; and they now load properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM