Turning one class instance into the instance of another class

This was an unpopular question, but I found out how to do what I wanted some time later. I will post the solution for anyone that would like to do what I wanted to accomplish.
So I wanted to make an instance of prints into a product page. I set up a control method in the print controller that created a new product instance, using the values of @print to set the product attribute values:

def turn_into_product
  @product = Product.new(image: @print.image, name: @print.name, \
      description: @print.description, user_id: @print.user_id, print_id: @print.id, \
   creator: @print.user.username)
respond_to do |format|
  if @product.save
    format.html { redirect_to @product, notice: 'Product was successfully created.' }
    format.json { render :show, status: :created, location: @product }
    format.html { render :new }
    format.json { render json: @product.errors, status: :unprocessable_entity }

I then made the connection to this method in the route file:

resources :prints do
  member do
    put 'flag', 'turn_into_product'

Finally, I used a ‘put’ call link_to button on the print show page:

<%= link_to "Turn into Product", turn_into_product_print_path(@print), method: :put, class: "btn btn-success" %>

And voila, New product instance with all the attributes, including images included. At the time of the question I did not have a solid grasp of html method calls in link_to or how to use routes for put methods. I also did not know that you could create instance of another class within a foreign controller. Now that I do, the possibilities seem to have multiplied.

Browse More Popular Posts

Leave a Comment