Can't get user_id in database after Ajax call - ruby-on-rails

In javascript I do an ajax call to the create function of deliveries_controller. This puts a new Delivery in the database with a product and quantity. I also try to put the current_user as user_id in the database, but for some reason it stays nil in the database.
My ajax call:
$.ajax({
type: "POST",
url: "/deliveries",
data: { delivery: {ingredient: "meel", quantity: "800", scenario_id: "3"} },
success: function(){
alert('Success!');
},
error: function(){
alert('No success');
}
});
I just pass some dummy data to test it all out.
and my deliveries_controller:
class DeliveriesController < ApplicationController
protect_from_forgery
def index
#storages = Storage.where(user_id: current_user)
end
def addQuantity
#storage = Storage.where(user_id: current_user.id)
#storage.update_all ("quantity = (quantity+200)")
redirect_to deliveries_url
end
def create
#delivery = Delivery.new(delivery_params)
respond_to do |format|
if #delivery.save
format.html do
render :nothing => true
end
format.json { render json: #delivery.to_json }
else
format.html { render :nothing => true} ## Specify the format in which you are rendering "new" page
format.json { render json: #delivery.errors } ## You might want to specify a json format as well
end
end
end
private
def delivery_params
params.require(:delivery).permit(:user_id, :ingredient, :quantity, :scenario_id)
end
end
New entries are created in the database, but whichever way I try to pass the user_id as param it isn't saved in the database.
I tried it like:
#delivery = Delivery.new(delivery_params, :user_id => current_user),
#user_id = current_user
#delivery = Delivery.new(delivery_params, #user_id)
and
params.require(:delivery).permit(:user_id, :ingredient, :quantity, :scenario_id).merge(user_id: current_user)
log:
Started POST "/deliveries" for 127.0.0.1 at 2014-11-03 12:59:37 +0100
Processing by DeliveriesController#create as */*
Parameters: {"delivery"=>{"ingredient"=>"meel", "quantity"=>"800", "scenario_id"=>"3"}}
Can't verify CSRF token authenticity
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."remember_token" = 'da39a3ee5e6b4b0d3255bfef95601890afd80709' LIMIT 1
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."remember_token" = 'da39a3ee5e6b4b0d3255bfef95601890afd80709' LIMIT 1
(0.0ms) begin transaction
SQL (0.2ms) INSERT INTO "deliveries" ("created_at", "ingredient", "quantity", "scenario_id", "updated_at") VALUES (?, ?, ?, ?, ?) [["created_at", "2014-11-03 11:59:37.253274"], ["ingredient", "meel"], ["quantity", 800], ["scenario_id", 3], ["updated_at", "2014-11-03 11:59:37.253274"]]
(12.5ms) commit transaction
Rendered text template (0.0ms)
Completed 200 OK in 24ms (Views: 0.8ms | ActiveRecord: 13.1ms)
but the user_id for Delivery stays nil. How would I pass the user_id from the current_user so it's saved in the database with the json I retrieve from the ajax call?
Thanks in advance
EDIT:
I fixed it the following way:
I send json data to javascript with content_tag:
= content_tag(:div,"", id: "storages", data:{url: Storage.where(user_id: current_user)})
this data is handled, and the user_id is suddenly accepted :)
thanks for the help!

Try this instead
#delivery = current_user.deliveries.new(delivery_params)

It should be
#delivery = Delivery.new(delivery_params.merge(user: current_user))
OR
#delivery = Delivery.new(delivery_params)
#delivery.user = current_user

Put current user_id on hidden field on HTML and send it with ajax like other params

Related

Use the image inserted in SummerNote in Ruby on Rails by linking CarrierWave and Cloudinary

I am in the process of creating a web app with Ruby on Rails.
I introduce SummerNote to make the article creation form user-friendly.
We have also introduced CarrierWave for user avatars.
Iā€™m using Heroku in production.
However, Heroku is going to erase images after 24h. So I added Cloudinary as an addon for keeping images on Heroku.
But the images inserted in the text field in SummerNote was erased.
I am in trouble because I do not know how to link summer note, carrier wave and Cloudinary.
Does anyone know how to link to SummerNote and carrier wave and Cloudinary?
My CODE
summernote-init.coffee
sendFile = (file, toSummernote) ->
data = new FormData
data.append 'upload[image]', file
$.ajax
data: data
type: 'POST'
url: '/uploads'
cache: false
contentType: false
processData: false
success: (data) ->
img = document.createElement('IMG')
img.src = data.url
console.log data
img.setAttribute('id', "sn-image-#{data.upload_id}")
toSummernote.summernote 'insertNode', img
deleteFile = (file_id) ->
$.ajax
type: 'DELETE'
url: "/uploads/#{file_id}"
cache: false
contentType: false
processData: false
$(document).on 'turbolinks:load', ->
$('[data-provider="summernote"]').each ->
$(this).summernote
lang: 'ja-JP'
height: 400
callbacks:
onImageUpload: (files) ->
sendFile files[0], $(this)
onMediaDelete: (target, editor, editable) ->
upload_id = target[0].id.split('-').slice(-1)[0]
console.log upload_id
if !!upload_id
deleteFile upload_id
target.remove()
image_uploader.rb
class ImageUploader < CarrierWave::Uploader::Base
include Cloudinary::CarrierWave
process :convert => 'png'
end
uploaders_controller.rb
class UploadsController < ApplicationController
def create
#upload = Upload.new(upload_params)
#upload.save
respond_to do |format|
format.json { render :json => { url: #upload.image.url, upload_id: #upload.id } }
end
end
def destroy
#upload = Upload.find(params[:id])
#remember_id = #upload.id
#upload.destroy
FileUtils.remove_dir("#{Rails.root}/public/uploads/upload/image/#{#remember_id}")
respond_to do |format|
format.json { render :json => { status: :ok } }
end
end
private
def upload_params
params.require(:upload).permit(:image)
end
end
Referred to site
MyError
terminal
Started POST "/uploads" for ::1 at 2020-05-19 13:46:50 +0900
Processing by UploadsController#create as */*
Parameters: {"upload"=>{"image"=>#<ActionDispatch::Http::UploadedFile:0x00007fc262966fc8 #tempfile=#<Tempfile:/var/folders/1v/z9ljm971349c50_qs5f5wy_h0000gn/T/RackMultipart20200519-19326-wz6m90.jpg>, #original_filename="jiyu.jpg", #content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"upload[image]\"; filename=\"jiyu.jpg\"\r\nContent-Type: image/jpeg\r\n">}}
(0.1ms) begin transaction
SQL (0.5ms) INSERT INTO "uploads" ("image", "created_at", "updated_at") VALUES (?, ?, ?) [["image", "dtcgxdmlua3jd5ddxkpg.png"], ["created_at", "2020-05-19 04:46:50.050482"], ["updated_at", "2020-05-19 04:46:50.050482"]]
SQL (0.1ms) UPDATE "uploads" SET "image" = 'image/upload/v1589863584/dtcgxdmlua3jd5ddxkpg.png' WHERE "uploads"."id" = ? [["id", 7]]
(1.6ms) commit transaction
Completed 200 OK in 1710ms (Views: 0.2ms | ActiveRecord: 2.4ms)
Started GET "/posts/null" for ::1 at 2020-05-19 13:46:51 +0900
Processing by PostsController#show as HTML
Parameters: {"id"=>"null"}
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ? [["id", 1], ["LIMIT", 1]]
Post Load (0.2ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT ? [["id", 0], ["LIMIT", 1]]
Completed 404 Not Found in 4ms (ActiveRecord: 0.6ms)
ActiveRecord::RecordNotFound (Couldn't find Post with 'id'=null):
my localhost
When I check the dashboard of Cloudinary, the image is saved but not displayed.
Can you tell me how to solve it?
Or what do I need to know?

How to use find_or_create in create action?

I want to use find_or_create method in my game dates controller. I don't know how to use that method in create action, when params are in game_date_params. Any suggestion how can I extract date from game_date_params?
class GameDatesController < ApplicationController
before_action :authenticate_user!
before_action :authenticate_admin
def index
#game_dates = GameDate.all
#showcases = Showcase.joins(:game_dates)
end
def new
#game_date = GameDate.new
#game_date.referee_stats.build
end
def create
#game_date = GameDate.new(game_date_params)
if #game_date.save
redirect_to showcases_path
flash[:success] = "Game date created"
else
render 'new'
end
end
def show
#game_date = GameDate.find(params[:id])
end
def destroy
#game_date = GameDate.find(params[:id]).destroy
redirect_to root_url
flash[:success] = "Game date deleted"
end
private
def game_date_params
params.require(:game_date).permit(:date, referee_stats_attributes: [ :games_count, :showcase_id ])
end
This is output from POST action:
Started POST "/game_dates" for 127.0.0.1 at 2016-04-01 10:21:44 +0200
Processing by GameDatesController#create as HTML Parameters:
{"utf8"=>"āœ“",
"authenticity_token"=>"jmuOmMCO/WTFIkxrsw5l2cPVMqZAl7h11f281I+OyoHH3ddwKoB9ANAqvQEHulR88c7fzQXnnIaxs8FChMCjqw==",
"game_date"=>{"date(1i)"=>"2016", "date(2i)"=>"4", "date(3i)"=>"1",
"referee_stats_attributes"=>{"0"=>{"games_count"=>"4",
"showcase_id"=>"1"}}}, "commit"=>"Create Game date"} User Load
(0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER
BY "users"."id" ASC LIMIT 1 [["id", 1]] GameDate Load (0.4ms)
SELECT "game_dates".* FROM "game_dates" WHERE "game_dates"."date" IS
NULL LIMIT 1 (0.2ms) BEGIN SQL (0.4ms) INSERT INTO "game_dates"
("date", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING
"id" [["date", "2016-04-01"], ["created_at", "2016-04-01
08:21:44.864669"], ["updated_at", "2016-04-01 08:21:44.864669"]] SQL
(0.4ms) INSERT INTO "referee_stats" ("games_count", "showcase_id",
"game_date_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4,
$5) RETURNING "id" [["games_count", 4], ["showcase_id", 1],
["game_date_id", 7], ["created_at", "2016-04-01 08:21:44.866897"],
["updated_at", "2016-04-01 08:21:44.866897"]] (18.1ms) COMMIT
Redirected to http://localhost:3000/showcases Completed 302 Found in
31ms (ActiveRecord: 20.1ms)
GameDate.find_or_create_by(game_date_params) would find record with ALL game_date_params, so you could do this by finding with specific params like date and assign rest of attributes to it via block. for example:
def create
# find or initialize the record
#game_date = GameDate.find_or_initalize_by(date: game_date_params[:date]) do |game_date|
# Accept nested attributes as well
game_date.assign_attributes(game_date_params)
end
if #game_date.save
redirect_to showcases_path
flash[:success] = "Game date created"
else
render 'new'
end
end
See also: find_or_create_by and AttributesAssignment API docs
It should be like :
def create
#game_date = GameDate.find_or_create_by(game_date_params)
if #game_date.present?
redirect_to showcases_path
flash[:success] = "Game date created"
else
render 'new'
end
end
Create action is for creating an object after the new action has been called and update action if the same but for edit. Mixing create & update logic i not a good idea. Maybe you should rethink what are you trying to do in your views.

How to pass blob url to rails create method by ajax

I want to upload a voice sound in my Rails project.
The recording works fine to download, but I can't send the data to rails server.
recorder && recorder.exportWAV(function (blob) {
var url = URL.createObjectURL(blob);
console.log(url);
$.ajax({
type: "POST",
url: "/voices",
data: {voice: {sound: url}}
});
});
In server log there is a post data, but sound was not created.
Started POST "/voices" for ::1 at 2015-12-08 20:43:16 +0900
Processing by VoicesController#create as */*
Parameters: {"voice"=>{"sound"=>"blob:http%3A//localhost%3A3000/3ad3859e-b960-44b8-ba18-20727e739bab"}}
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]]
Profile Load (0.3ms) SELECT "profiles".* FROM "profiles" WHERE "profiles"."user_id" = $1 LIMIT 1 [["user_id", 1]]
(0.2ms) BEGIN
SQL (0.5ms) INSERT INTO "voices" ("sound", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id" [["sound", nil], ["created_at", "2015-12-08 11:43:16.254713"], ["updated_at", "2015-12-08 11:43:16.254713"]]
(0.6ms) COMMIT
Completed 500 Internal Server Error in 135ms (ActiveRecord: 3.4ms)
How can I pass the sound blob data to rails server?
voices_controller.rb
class VoicesController < ApplicationController
#voice = Voice.new(voice_params)
respond_to do |format|
if #voice.save
format.html { redirect_to root_path, notice: 'voice was successfully created.' }
format.json { render :show, status: :created, location: root_path }
else
format.html { render :new }
format.json { render json: #voice.errors, status: :unprocessable_entity }
end
end
def voice_params
params.require(:voice).permit(:sound, :user_id)
end
end
app/models/voice.rb
class Voice < ActiveRecord::Base
belongs_to :phrase
belongs_to :user
mount_uploader :sound, SoundUploader
end
Another attempt
recorder && recorder.exportWAV(function (blob) {
var url = URL.createObjectURL(blob);
console.log(url);
var formData = new FormData();
formData.append('voice[sound]', url);
$.ajax({
type: "POST",
url: "/voices",
data: formData
});
});
This codes ends up with a error Uncaught TYpeError: Illegal invocation.
Not sure, if you are trying to post the data correctly or have your models setup properly. you need to save your audio as a file, using File.open(filename, w)
SQL (0.5ms) INSERT INTO "voices" ("sound", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id" [["sound", nil], ["created_at", "2015-12-08 11:43:16.254713"], ["updated_at", "2015-12-08 11:43:16.254713"]]
The SQL, is suggesting, that nothing is getting passed to "sound" field.
if you are passing it as a blob, you need to set the column accordingly, if not done entirely, however better option would be 2)
Send and save the audio data as a file. Have a look at link
formData.append('voice[sound]', url); # Comment this
formData.append('voice[sound]', blob); # This will send the actual data to your server and not the blob url. then your carrierwave will have the file data, which it can save.

File_size validation with file_validators gem unpermitted parameter

I added the file_validators gem to my app and called the validation in my vehicle_image.rb model that you can see below.
After attempting to upload a new image, I receive a unpermitted parameters message in the Rails console. I suspect the error has something to do with strong parameters? I attempted to assign the image prior to the if #vehicle.save but was unsuccessful.
edit:vehicle_image.rb
class VehicleImage < ActiveRecord::Base
belongs_to :vehicle
validates :image, file_size: { less_than_or_equal_to: 500.kilobytes, message: "Image must be less that 500kbs" }
mount_uploader :image, ImageUploader
def set_to_primary_and_save
VehicleImage.where(vehicle: vehicle).update_all(primary: false)
self.primary = true
save
end
end
stack trace
Started PATCH "/vehicles/65" for 127.0.0.1 at 2015-11-05 14:03:06 -0500
Processing by VehiclesController#update as HTML
Parameters: {"utf8"=>"āœ“", "authenticity_token"=>"o6W0JsKzxGe9D1z6VA2WeXW3b4JBVsfvYDvM4ANf4Eo5wVFBn1e31y+oKdLIsWFy41WXeW1BUenCzKTE6tni1Q==", "vehicle"=>{"make"=>"Pontiac", "model"=>"GTO", "year"=>"1967", "production_date"=>"January 5, 1968", "engine"=>"454 ", "transmission"=>"4 Speed Muncie", "trim"=>"Red", "color"=>"Black", "options"=>"Tinted Glass, Hurst Shifter", "location"=>"Milton, Ontario", "description"=>"sdfsdfdsf", "vehicle_images"=>{"image"=>[#<ActionDispatch::Http::UploadedFile:0x007f4adfa1c738 #tempfile=#<Tempfile:/tmp/RackMultipart20151105-7060-d0j694.jpg>, #original_filename="switzerland-3840x2160-alps-mountauns-stars-night-5713.jpg", #content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"vehicle[vehicle_images][image][]\"; filename=\"switzerland-3840x2160-alps-mountauns-stars-night-5713.jpg\"\r\nContent-Type: image/jpeg\r\n">], "image_cache"=>""}}, "commit"=>"Save", "id"=>"65"}
Vehicle Load (0.1ms) SELECT "vehicles".* FROM "vehicles" WHERE "vehicles"."id" = ? ORDER BY created_at DESC LIMIT 1 [["id", 65]]
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 6]]
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 6]]
Unpermitted parameter: vehicle_images
(0.0ms) begin transaction
(0.0ms) commit transaction
(0.1ms) begin transaction
SQL (0.3ms) INSERT INTO "vehicle_images" ("image", "vehicle_id", "primary", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?) [["image", "switzerland-3840x2160-alps-mountauns-stars-night-5713.jpg"], ["vehicle_id", 65], ["primary", "t"], ["created_at", "2015-11-05 19:03:06.685379"], ["updated_at", "2015-11-05 19:03:06.685379"]]
(18.5ms) commit transaction
Redirected to http://localhost:3000/vehicles/65
Completed 302 Found in 2474ms (ActiveRecord: 19.4ms)
vehicles_controller.rb
class VehiclesController < ApplicationController
def index
scope = Vehicle.approved
scope = scope.filter_by_make(params[:makes]) if params[:makes].present?
scope = scope.filter_by_year(params[:years]) if params[:years].present?
#vehicles = scope
authorize #vehicles
end
def show
#vehicle = Vehicle.find(params[:id])
#primary_image, #images = #vehicle.primary_and_all_vehicle_images
end
def new
#vehicle = Vehicle.new
authorize #vehicle
end
def create
#vehicle = Vehicle.new(vehicle_params)
#vehicle.user = current_user
authorize #vehicle
if #vehicle.save
add_vehicle_images if params[:vehicle][:vehicle_images][:image]
create_registry_request(#vehicle)
flash[:notice] = "The Vehicle was sent to the Administrator for Approval. You will be notified in your Dashboard if your vehicle was approved or denied."
redirect_to current_user
else
flash[:error] = "There was an error saving the Vehicle to the Registry. Please try again."
render :new
end
end
def edit
#vehicle = Vehicle.find(params[:id])
authorize #vehicle
#primary_image, #images = #vehicle.primary_and_all_vehicle_images
end
def update
#vehicle = Vehicle.find(params[:id])
authorize #vehicle
if #vehicle.update_attributes(vehicle_params)
add_vehicle_images if params[:vehicle][:vehicle_images][:image]
flash[:notice] = "The Vehicle entry was updated."
redirect_to #vehicle
else
flash[:error] = "There was an error updating the Vehicle. Please try again."
#primary_image, #images = #vehicle.primary_and_all_vehicle_images
render :edit
end
end
def re_edit
#vehicle = Vehicle.find(params[:id])
authorize #vehicle
#primary_image, #images = #vehicle.primary_and_all_vehicle_images
end
def resubmit
#update and new request
#vehicle = Vehicle.find(params[:id])
authorize #vehicle
if #vehicle.update_attributes(vehicle_params)
add_vehicle_images if params[:vehicle][:vehicle_images][:image]
Vehicle.transaction do
#vehicle.active_registry_request.archive
create_registry_request(#vehicle)
end
flash[:notice] = "The Vehicle entry was updated and sent to the Administrator. Please wait for Approval."
redirect_to #vehicle
else
flash[:error] = "There was an error updating the Vehicle. Please try again."
#primary_image, #images = #vehicle.primary_and_all_vehicle_images
render :re_edit
end
end
private
def vehicle_params
params.require(:vehicle).permit(:make, :model, :year, :production_date, :engine, :transmission, :trim, :color, :options, :location, :description, vehicle_images_attributes: [:image])
end
def add_vehicle_images
params[:vehicle][:vehicle_images][:image].each_with_index do |img, i|
image = #vehicle.vehicle_images.build(image: img)
image.primary = true if i == 0
image.save!
end
end
def create_registry_request(vehicle)
RegistryRequest.create!(vehicle: vehicle)
end
end
Parameters: {
# ... snip ...
"vehicle" => { # ... snip ...
"vehicle_images"=>{ # ... snip ... }
}
}
But the parameter whitelist is specified as:
params.require(:vehicle).permit(..., vehicle_images_attributes: [:image])
"vehicle_images" is not equal to "vehicle_images_attributes", thus the message:
Unpermitted parameter: :vehicle_images
Either the form or the whitelist needs to change so that the key in the params hash matches the argument in permit.
Normally the _attributes suffix is added to the form when we use accepts_nested_attributes_for, but you don't appear to be doing that.

How can I update another Model using a Callback?

I'm working with a Model called Recover. Prior to creating the model I would like to save the boolean attribute, Combo.occupied = true using the Recover.combo_id attribute as a reference.
It appears my SQL is executing the query properly, but it is not saving this attribute. How can I save Combo.occupied = true?
recover.rb:
before_create :checkin
protected
def checkin
x = Combo.find_by_id(combo_id).occupied =
true
end
Rails Console:
Started POST "/recovers" for 127.0.0.1
at 2011-01-06 17:07:24 -0800
Processing by
RecoversController#create as HTML
Parameters: {"utf8"=>"āœ“",
"authenticity_token"=>"o1Iu3Y9/rVBOZPoDUgVP/tRfQ8GxbdWC40DbPq9YxUE=",
"recover"=>{"combo_id"=>"4",
"email"=>"jz#marin.edu"},
"commit"=>"Create Recover"} Recover
Load (0.2ms) SELECT "recovers"."id"
FROM "recovers" WHERE
("recovers"."email" =
'justin.zollars#marin.edu') LIMIT 1
Recover Load (0.1ms) SELECT
"recovers"."id" FROM "recovers" WHERE
("recovers"."combo_id" = 4) LIMIT 1
Combo Load (0.5ms) SELECT "combos".*
FROM "combos" WHERE ("combos"."id" =
4) LIMIT 1 AREL (0.5ms) INSERT INTO
"recovers" ("locker_number", "email",
"requests", "created_at",
"updated_at", "combo_id") VALUES
(NULL, 'justin.zollars#marin.edu',
NULL, '2011-01-07 01:07:24.287072',
'2011-01-07 01:07:24.287072', 4)
Redirected to
http://localhost:3000/recovers/14
Completed 302 Found in 119ms
RecoversController#create
def create
#recover = Recover.new(params[:recover])
respond_to do |format|
if #recover.save
format.html { redirect_to(#recover, :notice =>
'Recover was successfully created.') }
format.xml { render :xml => #recover, :status => :created,
:location => #recover }
else
format.html { render :action => "new" }
format.xml { render :xml => #recover.errors, :status =>
:unprocessable_entity }
end
end
end
You need to call save for the new value to be written to the database:
def checkin
combo = Combo.find_by_id(combo_id)
combo.occupied = true
combo.save!
end
This is easier if you use update_attribute. Also, if you have a belongs_to relationship, you can dispense with the find:
belongs_to :combo
def checkin
if combo # true unless combo_id is nil
combo.update_attribute(:occupied,true)
end
end
Note that update_attribute bypasses validation. If you need to validate, use update_attributes(:occupied=>true) instead.

Resources