When creating a record in Rails Controller, the following error occurs :
Started POST "/spr_type_courses" for 127.0.0.1 at 2018-06-27 08:11:01
+0500 Processing by SprTypeCoursesController#create as HTML Parameters: {"spr_type_course"=>{}} Unpermitted parameter:
:spr_type_course Sequence (3.0ms) select us.sequence_name from
all_sequences us where us.sequence_owner = 'PROJECT' and
us.sequence_name = upper('SPR_TYPECOURSES_seq') Primary Key (10.0ms)
SELECT cc.column_name FROM all_constraints c, all_cons_columns cc
WHERE c.owner = 'PROJECT' AND c.table_name = 'SPR_TYPECOURSES' AND
c.constraint_type = 'P' AND cc.owner = c.owner AND cc.constraint_name
= c.constraint_name Primary Key Trigger (3.8ms) SELECT trigger_name
FROM all_triggers
WHERE owner = 'PROJECT'
AND trigger_name = q'[PROJECT.SPR_TYPECOURSES_PKT]'
AND table_owner = 'PROJECT'
AND table_name = q'[SPR_TYPECOURSES]'
AND status = 'ENABLED'
SQL (5.3ms) INSERT INTO "PROJECT"."SPR_TYPECOURSES"
("TYPECOURSE_ID") VALUES (:a1) [["typecourse_id", 3623]] Completed 500
Internal Server Error in 61ms
ActiveRecord::NotNullViolation (OCIError: ORA-01400: cannot insert
NULL into ("PROJECT"."SPR_TYPECOURSES"."DATE_BEGIN"): INSERT INTO
"PROJECT"."SPR_TYPECOURSES" ("TYPECOURSE_ID") VALUES (:a1)):
app/controllers/spr_type_courses_controller.rb:17:in `create'
What can this mean and what needs to be done to correct it?
class SprTypeCoursesController < ApplicationController
before_action :set_spr_type_course, only: [:show, :update, :destroy]
def index
#spr_type_courses = SprTypeCourse.all
render json: #spr_type_courses
end
def show
render json: #spr_type_course
end
def create
#spr_type_course = SprTypeCourse.new(spr_type_course_params)
if #spr_type_course.save
render json: #spr_type_course, status: :created, location: #spr_type_course
else
render json: #spr_type_course.erros, status: :unprocessable_entity
end
end
def update
if #spr_type_course.update(spr_type_course_params)
render json: #spr_type_course
else
render json: #spr_type_course.errors, status: :unprocessable_entity
end
end
def destroy
#spr_type_course.destroy
end
private
def set_spr_type_course
#spr_type_course = SprTypeCourse.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def spr_type_course_params
params.permit(
:typecourse_id,
:date_begin,
:date_end,
:name,
:comments,
:active_id
)
end
end
Your spr_type_course_params is the problem.
As you can see in the error log, the spr_type_course parameter is not being allowed in the strong parameters. Also, spr_type_course parameter is empty. Please review the submitted form too.
{"spr_type_course"=>{}} Unpermitted parameter:
Change it by the following:
def spr_type_course_params
# here I assume the typecourse_id, date_begin etc params are all
# included in spr_type_course schema
params.require(:spr_type_course).permit(
:typecourse_id,
:date_begin,
:date_end,
:name,
:comments,
:active_id
)
end
Related
Through the terminal I can make the CRUD Syllabus, but when I do it through my program's interface it doesn't allow me to "create" and does the ROLLBACK. How to debug this? I've tried it in so many ways, I don't know exactly what's going on. The strangest thing is that I've always managed to do this through the terminal.
my controller
before_action :set_syllabus, only: [:show, :update, :destroy]
def show
if #syllabus
scheduled_dates = JSON.parse #syllabus.scheduled_dates
# interests_array = #syllabus.student_interests.pluck(:data)
if current_student.status != "freemium"
render json: {
goal: #syllabus.goal,
objective: #syllabus.objective,
level: #syllabus.level,
estimate: #syllabus.estimate,
interests: #syllabus.interests,
skills: #syllabus.skills,
schedule: {
dates: scheduled_dates,
minutes: #syllabus.scheduled_minutes
}
# }.merge({:interests => interests_array })
}
else
render json: {
blocked: true,
goal: #syllabus.goal,
objective: #syllabus.objective,
level: #syllabus.level,
estimate: #syllabus.estimate,
interests: #syllabus.interests,
skills: #syllabus.skills,
schedule: {
dates: scheduled_dates,
minutes: #syllabus.scheduled_minutes
}
# }.merge({:interests => interests_array })
}
end
else
render json: {
errors: "Record not found."
}, status: 404
end
end
def create
#syllabus = Syllabus.new(syllabus_params)
if #syllabus.save
render json: #syllabus.as_json, status: :created
else
render json: {
errors: #syllabus.errors
}, status: :unprocessable_entity
end
end
def update
if #syllabus.update(syllabus_params)
render json: #syllabus.as_json(except: [:id]), status: :ok
else
render json: {
errors: #syllabus.errors
}, status: :unprocessable_entity
end
end
def destroy
if #syllabus.destroy
render :no_content
else
render json: { errors:
breweries.errors.full_messages
}, status: :unprocessable_entity
end
end
private
def set_syllabus
#syllabus = Syllabus.find_by(student_id: params[:id])
end
def syllabus_params
params.permit(
:student_id,
:objective,
:level,
:goal,
:estimate,
:interests,
:skills,
:scheduled_dates,
:scheduled_minutes
)
end
end```
```[619aec90-7658-4825-aebb-82fc7aecc978] Started POST "/api/v1/students/syllabus" for ::1 to 2021-08-05 14:35:52 -0300
[619aec90-7658-4825-aebb-82fc7aecc978] Processing by Api::V1::SyllabusController#create as HTML
[619aec90-7658-4825-aebb-82fc7aecc978] Parameters: {"student_id"=>52776, "level"=>"Basic", "objective"=>"Be able to travel more smoothly", "goal"=>"Advanced ", "estimate"=>14.625, "scheduled_dates"=>["dom", "sab"], "scheduled_minutes"=>200, "interests"=>["Sports", ""], "syllabus"=> {"student_id"=>52776, "objective"=>"Be able to travel more smoothly", "level"=>"Basic", "goal"=>"Advanced", "estimate"=>14.625, "scheduled_dates"= >["dom", "sat"], "scheduled_minutes"=>200, "interests"=>["Sports", ""]}}
[619aec90-7658-4825-aebb-82fc7aecc978] Unpermitted parameters: :scheduled_dates, :interests, :syllabus
[619aec90-7658-4825-aebb-82fc7aecc978] (0.4ms) BEGIN
[619aec90-7658-4825-aebb-82fc7aecc978] ↳ app/controllers/api/v1/syllabus_controller.rb:49
[619aec90-7658-4825-aebb-82fc7aecc978] Student Load (0.5ms) SELECT "students".* FROM "students" WHERE "students"."id" = $1 LIMIT $2 [["id", 52776], [" LIMIT", 1]]
[619aec90-7658-4825-aebb-82fc7aecc978] ↳ app/controllers/api/v1/syllabus_controller.rb:49
[619aec90-7658-4825-aebb-82fc7aecc978] (0.2ms) ROLLBACK
[619aec90-7658-4825-aebb-82fc7aecc978] ↳ app/controllers/api/v1/syllabus_controller.rb:49
[619aec90-7658-4825-aebb-82fc7aecc978] Completed 422 Unprocessable Entity in 541ms (Views: 0.1ms | ActiveRecord: 5.2ms)```
The error is right there, unpermitted parameters.
You will need to add require(:syllabus) to your strong parameters.
params.require(:syllabus).permit(
:student_id,
:objective,
:level,
:goal,
:estimate,
:skills,
:scheduled_minutes
interests: [],
scheduled_dates: [],
)
I have the following controller:
class Api::V1::FeedbacksController < ApplicationController
before_action :authenticate_user!
def create
#feedback = current_user.feedbacks.create(
feedback_type: params[:selectedType],
message: params[:message]
)
json_response(#feedback)
end
private
def json_response(object, status = :ok)
render json: object, status: status
end
end
Feedback.rb
validates :message, presence: true, length: { in: 1..1000 }
This works great when message is between 1 to 1000 in length. If the controller is submitted more than 1000 characters, the controller is still respond back but without the error.
What is the right way in Rails 5 to have the controller return an error if the create method above fails?
The usual rails way is to test the return value of .save:
def create
#feedback = current_user.feedbacks.new(
feedback_type: params[:selectedType],
message: params[:message]
)
if #feedback.save
json_response(#feedback)
else
json_response(#feedback.errors, :some_other_status)
# you could also send #feedback directly and then in your JSON response handler
# to test if the json contains values in the object.errors array
end
end
private
def json_response(object, status = :ok)
render json: object, status: status
end
You can use this doc to find the right statuts code to return https://cloud.google.com/storage/docs/json_api/v1/status-codes
I'm having a hard time trying to figure out what's wrong in my code. Basically, I'm using Dropzone-js's file uploader, that uses drag and drop. I can't upload a file because it returns me a 404 error.
I searched through my logs and found that I had a problem in my controller, in the update function.
The controller :
class ChatRoomsController < ApplicationController
before_action :authenticate_user!
before_action :set_room, only: [:index, :new, :create, :show, :edit, :signal]
before_action :set_participant, only: [:signal]
def index
#chat_rooms = ChatRoom.all
end
def show
# Show room messages
#chat_room = ChatRoom.includes(:messages).find_by(id: params[:id])
#message = Message.new
#chat_room.participant?(current_user)
# TODO: get participant only once
if params[:guid]
if #participant = User.find(params[:guid])
#participant.joined_at = Time.now
#chat_room.add_to_call(#participant)
end
elsif params[:del]
if #participant = User.find(params[:del])
#chat_room.remove_from_call(#participant)
end
end
response = {
room: #chat_room,
# Get all call participants
users: #chat_room.call_users,
signals: deliver_signals!
}
respond_to do |format|
format.html
format.json { render json: response }
end
end
def new
#chat_room = ChatRoom.new
end
def edit
# Empty
end
def create
#chat_room = current_user.chat_rooms.build(chat_room_params)
if #chat_room.save
#group_room.users << current_user
redirect_to chat_rooms_path
else
render 'new'
end
end
def update
#chat_room = ChatRoom.find(id: params[:chat_room_id])
if #chat_room.update_resource(chat_room_params)
flash[:success] = 'test'
else
render 'edit'
end
end
def signal
signal = signal_params
signal[:chat_room] = #chat_room
signal[:sender] = User.find(signal[:sender])
signal[:recipient] = #participant
logger.info('Signal is ' + signal.to_param)
ChatRoomSignal.create! signal
head 204
end
def deliver_signals!
data = ChatRoomSignal.where recipient: #participant
# Destroy the signals as we return them, since they have been delivered
result = []
data.each do |signal|
result << {
signal_type: signal.signal_type,
sender_guid: signal.sender_id,
recipient_guid: signal.recipient_id,
data: signal.data,
chat_room_id: signal.chat_room_id,
timestamp: signal.created_at
}
end
data.delete_all
result
end
private
def set_participant
#participant = User.find(params[:user_id])
rescue ActiveRecord::RecordNotFound
# Retry with ID as GUID
#participant = User.where(id: params[:user_id]).first
raise unless #participant
end
def set_room
#chat_room = ChatRoom.includes(:messages).find_by(id: params[:chat_room_id])
end
def chat_room_params
params.require(:chat_room).permit(:title, :image)
end
def signal_params
params.permit(:sender, :signal_type, :data)
end
HTML code for file upload :
<div class="panel-body">
<%= form_for #chat_room, html: { multipart: true, class: "dropzone", id: "my-dropzone"} do |f| %>
<div class="dz-message needsclick">
<h3>Drop a file here</h3> or <strong>click</strong> to upload
</div>
<div class="fallback">
<% f.file_field :image, as: :file %>
<%= f.submit "Upload your file" %>
</div>
<% end %>
</div>
The error :
[ActionCable] [test#test.com] ChatRoomsChannel is transmitting the subscription confirmation
[ActionCable] [test#test.com] ChatRoomsChannel is streaming from chat_rooms_1_channel
Started PATCH "/chat_rooms/1" for 127.0.0.1 at 2017-06-09 01:44:26 +0200
Processing by ChatRoomsController#update as JSON
Parameters: {"utf8"=>"✓", "authenticity_token"=>"p8KEWBx7fmJmEhHgINmp5rnj+PVwGXfbPHxslSaA4Z/5zA6HIJzxeBjwcz/+GcDEQKKwPwjXNJVnBtfq7xu2qw==", "chat_rooms"=>{"image"=># <ActionDispatch::Http::UploadedFile:0x007f640e58f5b0 #tempfile=#<Tempfile:/tmp/RackMultipart20170609-2887-1nuat54.png>, #original_filename="Screenshot from 2017-04-12 12-47-21.png", #content_type="image/png", #headers="Content-Disposition: form-data; name=\"chat_rooms[image]\"; filename=\"Screenshot from 2017-04-12 12-47-21.png\"\r\nContent-Type: image/png\r\n">}, "id"=>"1"}
[1m[36mUser Load (0.2ms)[0m [1m[34mSELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?[0m [["id", 1], ["LIMIT", 1]]
[1m[36mChatRoom Load (0.2ms)[0m [1m[34mSELECT "chat_rooms".* FROM "chat_rooms" WHERE "chat_rooms"."id" = ? LIMIT ?[0m [["id", nil], ["LIMIT", 1]]
Completed 404 Not Found in 7ms (ActiveRecord: 0.3ms)
ActiveRecord::RecordNotFound (Couldn't find ChatRoom with 'id'={:id=>nil}):
app/controllers/chat_rooms_controller.rb:62:in `update'
Line 62 :
#chat_room = ChatRoom.find(id: params[:chat_room_id])
So it seems like my controller is not able to find the id parameter, but i don't understand why. And this is probably the error that causes my file to return 404 error.
Thanks for the time you will take to read my post.
You are using the wrong key to get the id, try with params[:id]:
#chat_room = ChatRoom.find(params[:id])
Also notice that the id: has been removed, since find will look for the id provided as parameter.
Also, you should update your chat_room_params method:
def chat_room_params
params.require(:chat_rooms).permit(:title, :image)
end
Since you are updating only 2 attributes, you could refactor your update method like this:
def update
#chat_room = ChatRoom.find(id: params[:chat_room_id])
#chat_room.title = chat_room_params[:title]
#chat_room.image = chat_room_params[:image]
if #chat_room.save(chat_room_params)
flash[:success] = 'test'
else
render 'edit'
end
end
Your params[:chat_room_id] seems to be a hash..
Try
#chat_room = ChatRoom.find(id: params[:chat_room_id][:id])
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.
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.