CarrierWave cancels file upload if resize processing done - ruby-on-rails

I am using CarrierWave gem to upload images. I accept any size, but when uploaded, it must be resized server side. Im using this code to do this:
class PictureUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
process resize_and_pad: [1280, 720]
# other things
end
But when I'm clicking submit on form, it simply redirects me to index of controller.
If I change resize_and_pad to any other resize such as resize_to_fit, resize_to_fill or resize_to_limit, nothing changes.
If I comment line with resize thing, all works fine except image doesn't resize of course.
In logs I see this when I have resize thing:
(0.0ms) begin transaction
(0.0ms) commit transaction
(0.0ms) begin transaction
(0.0ms) rollback transaction
And without it:
(0.0ms) begin transaction
SQL (1.0ms) INSERT INTO "pictures" ("user_id", "name", "description", "created_at", "updated_at", "file")
VALUES (?, ?, ?, ?, ?, ?)
[["user_id", 1], ["name", "aaaaaaaaa"], ["description", "sssssssssssss"], ["created_at", 2016-10-01 19:37:49 UTC], ["updated_at", 2016-10-01 19:37:49 UTC], ["file", "3fe28255-f698-4f82-a64a-b41a90bb92a8.jpg"]]
(125.9ms) commit transaction
(0.0ms) begin transaction
(0.0ms) commit transaction

Related

Rails - Devise's registration controller create action seems to trigger twice

I added this lines of code to create action:
def create
super
#card = Card.find(params[:card_id])
#card.update(:user_id=>current_user)
end
And everything works fine, user gets created, card gets updated, but after redirect this happens:
Couldn't find Card with 'id'=
Extracted source (around line #14):
def create
super
#card = Card.find(params[:card_id])
#card.update(:user_id=>current_user)
end
I checked my terminal to find out the reason why this happens, and it seems that create action triggers twice for no reason:
Started POST "/users" for ::1 at 2020-08-12 11:04:34 +0300
Processing by Users::RegistrationsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"q1W0+ZhzK85uHTcp1x4jKHvCG0ukIgj2JxZuAy6vuLQl/vPqJVu6eXSEWviYTnWC4cXAJk2xCJhl8mgoWzXIAA==", "user"=>{"name"=>"Терл Кабот", "email"=>"tafff1#gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "card_id"=>"2000012606"}, "commit"=>"Sign up"}
Card Load (1.0ms) SELECT "cards".* FROM "cards" WHERE "cards"."id" = $1 LIMIT $2 [["id", 2000012606], ["LIMIT", 1]]
(0.0ms)
BEGIN
User Exists (1.0ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = $1 LIMIT $2 [["email", "tafff1#gmail.com"], ["LIMIT", 1]]
SQL (1.0ms) INSERT INTO "users" ("email", "encrypted_password", "name", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id" [["email", "tafff1#gmail.com"], ["encrypted_password", "$2a$12$qTrv/zFUxULi9sqWgYlY/uPjQoJsZxB8PJK2ae/e6YfAFT40ci47e"], ["name", "Терл Кабот"], ["created_at", "2020-08-12 08:04:35.174621"], ["updated_at", "2020-08-12 08:04:35.174621"]]
SQL (1.0ms) UPDATE "cards" SET "user_id" = $1, "updated_at" = $2 WHERE "cards"."id" = $3 [["user_id", 17], ["updated_at", "2020-08-12 08:04:35.178626"], ["id", 2000012606]]
(1.0ms) COMMIT
Redirected to http://localhost:3000/
Card Load (0.0ms) SELECT "cards".* FROM "cards" WHERE "cards"."id" = $1 LIMIT $2 [["id", nil], ["LIMIT", 1]]
Completed 404 Not Found in 378ms (ActiveRecord: 6.0ms)
ActiveRecord::RecordNotFound (Couldn't find Card with 'id'=):
is there any solution for this?
EDIT: I gave up and just changed card and user logic, now user belongs to card, so I dont have to update cards user_id from devises create action.
The card_id is nested in the user key, so it will be: params[:user][:card_id]

Rails Carrierwave: unable to save full url with after_action method

I want to save the full url of my uploaded images in a rails app using the CarrierWave gem. I update the entry just after the create action but it does not work. However, when I puts my variable, the full url appears but it only saves the identifier...
The Card controller, after_action method:
class CardsController < ApplicationController
before_action :set_card, only: [:show, :edit, :update, :destroy]
after_action :save_full_image_url, only: [:create, :update]
include Shortener
require 'carrierwave/orm/activerecord'
def save_full_image_url
c = #card
puts "URL: "+c.image_url.url
#card.update(image_url: c.image_url.url)
Rails.logger.info(#card.errors.inspect)
end
My Card model:
class Card < ApplicationRecord
validates :cta_button_url, :format => URI::regexp(%w(http https)), presence: { message: '%{value} : please enter valid url' }
validates :title, :subtitle, :cta_button_text, :cta_button_url, :presence => true
mount_uploader :image_url, ImageUploader
has_one :short_url
end
My full logs:
SQL (0.3ms) INSERT INTO "cards" ("letter_id", "title", "subtitle",
"image_url", "cta_button_text", "cta_button_url", "share_button")
VALUES (?, ?, ?, ?, ?, ?, ?) [["letter_id", 49], ["title",
"fsddssd"], ["subtitle", "fsdfsdfsd"], ["image_url", "10298593.jpg"],
["cta_button_text", "Visit site"], ["cta_button_url",
"http://www.testurl.com"], ["share_button", "t"]] (1.1ms) commit
transaction (0.1ms) begin transaction Card Load (0.2ms) SELECT
"cards".* FROM "cards" WHERE "cards"."id" = ? LIMIT ? [["id", 44],
["LIMIT", 1]] SQL (0.4ms) INSERT INTO "short_urls" ("card_id",
"token", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["card_id",
44], ["token", "PmK5vnuCU9Dczz995fz8Ddbf"], ["created_at", "2017-08-08
21:08:57.625325"], ["updated_at", "2017-08-08 21:08:57.625325"]]
(0.8ms) commit transaction Letter Load (0.2ms) SELECT "letters".*
FROM "letters" WHERE "letters"."id" = ? LIMIT ? [["id", 49],
["LIMIT", 1]] (0.1ms) begin transaction CoreBot Load (0.2ms)
SELECT "core_bots".* FROM "core_bots" WHERE "core_bots"."id" = ?
LIMIT ? [["id", 1], ["LIMIT", 1]] (0.1ms) commit transaction
Redirected to http://localhost:3000/dashboard/test URL:
http://localhost:3000/uploads/card/image_url/44/10298593.jpg
(0.1ms) begin transaction SQL (0.4ms) UPDATE "cards" SET
"image_url" = ? WHERE "cards"."id" = ? [["image_url",
"10298593.jpg"], ["id", 44]] (2.5ms) commit transaction
"10298593.jpg", cta_button_text: "Visit site", cta_button_url:
"http://www.testurl.com", share_button: true>, #messages={},
#details={}> Completed 302 Found in 60ms (ActiveRecord: 7.2ms)
When I log in the console "c.image_url.url" I get the full URL (http://localhost:3000/uploads/card/image_url/44/10298593.jpg) but when I update my entry, it only saves the end (10298593.jpg).
Any idea why I am not able to save the entire url even if I can get it in a variable before?
Problem solved! The issue was from the mount_uploader :image_url, ImageUploader
I created a "remote_image_url" and updated it with the full url. Now it works!

Why do I get a 500 error (undefined method 'to_model' on save of duplicated Ruby on Rails Model

I'm new to rails and still fuzzy on some things but here goes.
I am sending json post request to /microposts/10/duplicate.json to duplicate a micropost.
The route goes to microposts#duplicate
The Controller action is:
def duplicate
micropost = current_user.microposts.find(params[:id])
new_micropost = micropost.dup
respond_with new_micropost.save
end
The server logs for the request is:
Started POST "/microposts/15/duplicate.json" for 180.181.247.76 at 2015-09-06 11:00:38 +0000
Processing by MicropostsController#duplicate as JSON
Parameters: {"_json"=>15, "id"=>"15", "micropost"=>{}}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 2]]
Micropost Load (0.3ms) SELECT "microposts".* FROM "microposts" WHERE "microposts"."user_id" = ? AND "microposts"."id" = ? ORDER BY "microposts"."created_at" DESC LIMIT 1 [["user_id", 2], ["id", 15]]
(0.1ms) begin transaction
SQL (0.4ms) INSERT INTO "microposts" ("content", "user_id", "title", "link", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?) [["content", "RLCPYIIG"], ["user_id", 2], ["title", "herp"], ["link", "snerp"], ["created_at", "2015-09-06 11:00:38.576553"], ["updated_at", "2015-09-06 11:00:38.576553"]]
(11.7ms) commit transaction
Completed 500 Internal Server Error in 28ms (ActiveRecord: 12.8ms)
NoMethodError (undefined method `to_model' for true:TrueClass):
app/controllers/microposts_controller.rb:23:in `duplicate'
So the micropost is saved but I don't know why I get the 500 error.
Also, should I be using .require and .permit here? The only thing in params from the front end should be the id.
Any help would be appreciated.
I was recently getting a similar error when using respond_with.
Turned out I was just missing the corresponding view for my action when requesting a HTML response.
Unfortunately the error was rather cryptic with..
undefined method `to_model' for #<Array:0x007fc7c59ada50> Did you mean? to_xml
TLDR: Check you have a corresponding view.
Hope this helps someone.
Figured it out. I should be using PUT not POST here.

How to clone models in Ruby on Rails/ActiveRecord?

I'm trying to create many copies of a message to users:
users.each do |user|
new_message = message.clone
new_message.to = user
new_message.save!
end
However, this doesn't work after the 1st user. Here's part of the error message:
SQL (0.7ms) INSERT INTO "messages" ("content", "to_id") VALUES (?, ?) [["content", "abc"], ["to_id", 1]]
(2.5ms) commit transaction
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = 2 LIMIT 1
(0.0ms) begin transaction
SQL (0.5ms) INSERT INTO "messages" ("content", "id", "to_id") VALUES (?, ?, ?) [["content", "abc"], ["id", 6], ["to_id", 2]]
SQLite3::ConstraintException: PRIMARY KEY must be unique: INSERT INTO "messages" ("content", "id", "to_id") VALUES (?, ?, ?)
(0.0ms) rollback transaction
Completed 500 Internal Server Error in 130.1ms
ActiveRecord::StatementInvalid (SQLite3::ConstraintException: PRIMARY KEY must be unique: INSERT INTO "messages" ("content", "id", "to_id") VALUES (?, ?, ?)):
As you can see, the problem is that the 2nd time the loop runs, message.clone must contain the id of the previous new_message.
What is the proper way to clone message records for many users? I can, of course, manually copy each attribute (I have a lot more than just content and to_id) into a fresh new Message object. But I'd like to know if there's a better way.
You can use dup, with which the id, created_at and updated_at are set to nil. This will ensure that Primary Key exception is not thrown, however if there are other unique validations, they will fail. You'd have to handle them separately.
users.each do |user|
new_message = message.dup
new_message.to = user
new_message.save!
end

rails 3 accepts_nested_attributes_for not working when save

I have declared the accepts_nested_attributes_for and everything works fine but only when I save the model into the database, the nested model is not saved along the master model, anyone know why?
In my log/development.log file:
Started POST "/users/1/business_infos" for 127.0.0.1 at 2011-10-22 23:08:59 -0500
Processing by BusinessInfosController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Vw9GWH4cnr8z+PPged0mal/CVsbdBM1NcDehRb7zl7Q=", "business_info"=>{"business_name"=>"microsoft", "locations_attributes"=>{"0"=>{"address"=>"New York, NY"}, "1"=>{"address"=>""}, "2"=>{"address"=>""}}, "business_hours"=>"5am-7pm, Mon - Fri", "business_logo"=>#<ActionDispatch::Http::UploadedFile:0xa219684 #original_filename="rails.png", #content_type="image/png", #headers="Content-Disposition: form-data; name=\"business_info[business_logo]\"; filename=\"rails.png\"\r\nContent-Type: image/png\r\n", #tempfile=#<File:/tmp/RackMultipart20111022-28086-fbv7x6>>, "business_phone"=>"6666666666", "business_web_addr"=>"www.microsoft.com"}, "commit"=>"Create", "user_id"=>"1"}
[1m[36mUser Load (0.3ms)[0m [1mSELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1[0m [["id", "1"]]
[1m[35mSQL (4.9ms)[0m INSERT INTO "business_infos" ("business_addr", "business_hours", "business_logo", "business_name", "business_phone", "business_web_addr", "confirmed", "created_at", "multi_location", "qr_code", "updated_at", "user_id") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) [["business_addr", nil], ["business_hours", "5am-7pm, Mon - Fri"], ["business_logo", "/assets/business_logo/microsoft.png"], ["business_name", "microsoft"], ["business_phone", "6666666666"], ["business_web_addr", "www.microsoft.com"], ["confirmed", nil], ["created_at", Sun, 23 Oct 2011 04:08:59 UTC +00:00], ["multi_location", nil], ["qr_code", nil], ["updated_at", Sun, 23 Oct 2011 04:08:59 UTC +00:00], ["user_id", 1]]
[1m[36mBusinessInfo Load (0.2ms)[0m [1mSELECT "business_infos".* FROM "business_infos" WHERE "business_infos"."user_id" = 1 LIMIT 1[0m
[1m[35m (1.0ms)[0m UPDATE "business_infos" SET "qr_code" = '/assets/qr_code/microsoft.png', "updated_at" = '2011-10-23 04:09:00.314348' WHERE "business_infos"."id" = 8
Redirected to http://localhost:3000/users/1
Completed 302 Found in 613ms
if you see Parameters in the log, there contains a location_attributes(location model), which is the nested attributes for business_info model, but if you see the INSERT INTO "business_infos" query, there are no insertion to the location table!
I have posted a more detailed question at this link Rails mode accepts_nested_attributes_for working properly Any clue?

Resources