Are you wondering how to prepopulate a _form with a duplicated image?

When a user clicks on a featured_inspiration, the intention is to populate a new _form with data from that featured_inspiration. The data consists of :text and/or :image, allowing the user to save an existing Inspiration to their list of Inspirations.

The issue arises when :image fails to prepopulate while :text functions correctly.

controller

  def new
    existing_inspiration = Inspiration.find_by_id params[:inspiration_id]
    if existing_inspiration
      @inspiration = existing_inspiration.dup

      @inspiration.image_file_name = existing_inspiration.dup.image_file_name
      @inspiration.image_content_type = existing_inspiration.dup.image_content_type 
      @inspiration.image_file_size = existing_inspiration.dup.image_file_size
      @inspiration.image_updated_at = existing_inspiration.dup.image_updated_at

    else
      @inspiration = current_user.inspirations.build
    end
  end

Console

[41] pry(main)> Inspiration.last
  Inspiration Load (1.7ms)  SELECT  "inspirations".* FROM "inspirations"  ORDER BY "inspirations"."id" DESC LIMIT 1
=> #<Inspiration:0x007fa6d15ec9a8
 id: 13,
 conceal: false,
 user_id: 8,
 created_at: Fri, 26 Feb 2016 15:29:52 EST -05:00,
 updated_at: Fri, 26 Feb 2016 15:29:52 EST -05:00,
 likes: nil,
 name: "",
 image_file_name: nil, 
 image_content_type: nil, 
 image_file_size: nil, 
 image_updated_at: nil>

_form

<%= simple_form_for(@inspiration, html: { data: { modal: true } }) do |f| %> 
  <%= f.file_field :image %>
  <%= f.text_area :text %>
<% end %>

Here's how I got duplicating text to work.

UPDATE

suggested_inspirations

<% @inspirations.each do |inspiration| %>
  <%= link_to inspiration_path(inspiration) do %>
    <div class="box panel panel-default" style="width: 175px;">
      <% if inspiration.image.present? %>
        <div id="box">
          <%= link_to new_inspiration_path(inspiration_id: inspiration.id), data: { modal: true } do %>
            <div class="inspiration-image-button"><span class="glyphicon glyphicon-plus"></span></div>
          <% end %>
          <%= link_to image_tag(inspiration.image.url(:medium)), inspiration %>
        </div>
      <% end %>
      <% if inspiration.name.present? %>
        <div class="panel-body">
          <%= link_to new_inspiration_path(inspiration_id: inspiration.id), data: { modal: true } do %>
            <div class="inspiration-button"><span class="glyphicon glyphicon-plus"></span></div>
          <% end %>
          <%= inspiration.name %>
        </div>
      <% end %>
    </div>
  <% end %>
<% end %>

Answer №1

Have you ever considered trying something along the lines of:

@replica = existing_replica.clone
@replica.file_name = existing_replica.file_name

Instead of using clone, manually performing the "deep" copies.

You may find this discussion on the easiest method for duplicating an activerecord record helpful. It's a little dated, but there are some valuable insights and references to gems that facilitate "deep" copying.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the world of mongoose searching

Currently, I am setting up a search functionality for a Mongodb database using Mongoose. Here's what I have on the frontend: var searchQuery = { title: ($('#responseTitle').val()), text: ($('#responseKeywords&ap ...

Determining control points within the getBBox() method for SVG paths on Safari and Chrome

I am encountering an issue related to a bug documented here: https://code.google.com/p/svg-edit/wiki/BrowserBugs#getBBox_on_paths_with_curves_includes_control_points When dealing with arcs (defined by center, radius, startAngle, endAngle), I can calculate ...

Choose the data attribute value and incorporate it into the select dropdown options

I'm brand new to Vue.js. Specifically, the requirement is that the backend will input time slot values into the data-times attributes in array format. My task is to extract and update these time slots based on the selected location. If "Location 1" ...

Leverage Angular.js to retrieve information from current HTML documents

angular.js is a powerful tool for handling complex client-side JavaScript in web applications, but I'm also considering using it for simpler tasks. For instance, let's say I have a list with some items: <ul> <li data-id="1">Foo& ...

Press the delete button to remove both the box and text dynamically with JavaScript

My task involves managing a shopping list with delete buttons next to each item. I am trying to use JavaScript to remove both the button and the corresponding text when the button is clicked. So far, my attempts have been unsuccessful. I used document.getE ...

Tips for identifying selected rows in Material UI DataGrid

Currently, I am in the process of developing a website using React along with Material UI. My main focus right now is to identify which rows are currently selected in my DataGrid. To achieve this, I want to populate an array with the selected rows using t ...

Using jQuery, adjust the width of child elements within a container by applying dynamic CSS styling

I am attempting to dynamically set the width of several child elements using jQuery. Here is what I am trying to achieve: Obtain the count of the desired containers (since there will be multiple instances of the .steps-container class in the DOM) Iterate ...

Halt the execution of any additional code

I have a favor to ask: Character.count({'character.ownerid': msg.author.id}, function (err, count) { if (err) { throw err; } if (count > 3) { err.message = 'Exceeded character limit'; //create error ...

Exploring JSON data in React applications

Below is the code I am currently working with: export class Highlights extends React.Component { render() { return ( <div> {JSON.stringify(this.props.highlights_data.data)} </div> ) ...

Key code problem - Struggling to block the entry of the % symbol

On my HTML page, I have an input text field that should only accept number keys and left/right arrow on the keyboard. I attempted to implement this using JavaScript, but encountered a problem. <input onkeypress="return allowNumberOnly(event)" /> fu ...

Incorporate the select2 plugin into your AngularJS project for enhanced functionality

In my AngularJS application, I am utilizing the select2 plugin to showcase a list of entities (tags). This snippet shows part of my template: select.ddlTags(ui-select2="select2Options", multiple, ng-model="link.tags") option(ng-repeat="tag in tags", ...

Accessing URL query parameters with axios

Currently, I am in the process of integrating APIs for my project where I am using React on the frontend and Django on the backend. To handle this integration, Axios is proving to be quite useful. On the frontend, I make a call to a specific URL structure ...

Transform XLS files into JSON format seamlessly by leveraging the power of Sheetjs and FileReader.js

I have been attempting to transform an uploaded XLSX file into JSON format using https://github.com/bgrins/filereader.js for handling the upload process and https://github.com/SheetJS for the actual conversion of the file. Below is the code I am currently ...

A customizable JavaScript NPM Package designed to specifically escape XML special characters while preserving the integrity of the XML tags

Seeking recommendations for a JavaScript npm package that can escape the values in an XML document while preserving the XML tags. Ideally, looking for a solution that only allows letters A-Z (upper and lower case), digits 0-9, and spaces within the value ...

Pressing the "Enter" key will submit the contents of

Hello, I have recently created a new chat box and everything seems to be working fine. However, I am facing an issue with submitting a message when I press enter (to go to the function Kucaj()). Can anyone provide assistance with this problem? I tried ad ...

Issue with Bootstrap form validation not displaying errors until form submission

I have been working on validating my contact form using Bootstrap 4. Currently, the validation only occurs after submission, but I would like it to highlight errors as soon as incorrect information is entered in a field and the user moves to another field. ...

Incorporate personalized feedback into a datatable with server-side processing

Trying to implement server-side processing for a datatable loaded from an AJAX response using this specific example The server response being received is as follows: {"msg":null,"code":null,"status":null,"result":[{"aNumber":"3224193861","bNumber":"32159 ...

Problem encountered when utilizing dat.GUI in a three.js demonstration

I recently experimented with using dat.GUI in a specific three.js example. To integrate a GUI for adjusting mesh opacity, I made the following code modifications. var loader=new THREE.VTKLoader(); loader.load ("models/vtk/bunny.vtk", function(geom){ var ...

Transferring PHP array data to JavaScript without being exposed in the source code

In the process of creating a historical database, I am currently handling over 2,000 photos that require categorization, out of which approximately 250 have already been uploaded. To efficiently store this data, I have set up a MySQL database with 26 field ...

Do we need to use initializeApp() from Firebase 9 when setting up email login?

Similar Topic: Exploring the Fun of Firebase's initializeApp(config) Function When integrating Gmail login, is it necessary for an app to invoke intializeApp()? Although the documentation specifies that a config object must be provided to initializ ...