ActiveRecord::RecordNotDestroyed - ruby-on-rails

I can't understand why the destroy method doesn't work only in just one class.
That's the code:
# DELETE /routes/1
# DELETE /routes/1.json
def destroy
#route.destroy
respond_to do |format|
format.html { redirect_to routes_url, notice: 'Route was successfully destroyed.' }
format.json { head :no_content }
end
end
I also tried this:
def destroy
#route = Route.find(params[:id])
if #route.destroy
#route.destroy
end
redirect_to routes_url
end
but with the same result.
Can you help me? thanks
EDIT.
this is the full error.
Started DELETE "/routes/10" for 127.0.0.1 at 2015-09-22 18:24:24 +0200
Processing by RoutesController#destroy as HTML
Parameters: {"authenticity_token"=>"XP84FdlatYqkyB31qi872vNSo2aQjmkjKFlvjCnmsbr5M7nL11eo/QF+mlantF+CgLvag6leu4k4dGj8SMSOog==", "id"=>"10"}
Route Load (0.3ms) SELECT "routes".* FROM "routes" WHERE "routes"."id" = ? LIMIT 1 [["id", 10]]
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
(0.1ms) begin transaction
Reservation Load (0.2ms) SELECT "reservations".* FROM "reservations" WHERE "reservations"."route_id" = ? [["route_id", 10]]
(0.2ms) rollback transaction
Completed 500 Internal Server Error in 63ms (ActiveRecord: 3.4ms)
ActiveRecord::RecordNotDestroyed (ActiveRecord::RecordNotDestroyed):
app/controllers/routes_controller.rb:60:in `destroy'
Rendered /home/railsuser/.rvm/gems/ruby-2.2.2/gems/actionpack-4.2.1/lib/action_dispatch/middleware/templates/rescues/_source.erb (12.3ms)
Rendered /home/railsuser/.rvm/gems/ruby-2.2.2/gems/actionpack-4.2.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (6.0ms)
Rendered /home/railsuser/.rvm/gems/ruby-2.2.2/gems/actionpack-4.2.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.8ms)
Rendered /home/railsuser/.rvm/gems/ruby-2.2.2/gems/actionpack-4.2.1/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (49.7ms)
Rendered /home/railsuser/.rvm/gems/ruby-2.2.2/gems/web-console-2.2.1/lib/web_console/templates/_markup.html.erb (0.6ms)
Rendered /home/railsuser/.rvm/gems/ruby-2.2.2/gems/web-console-2.2.1/lib/web_console/templates/_inner_console_markup.html.erb within layouts/inlined_string (0.6ms)
Rendered /home/railsuser/.rvm/gems/ruby-2.2.2/gems/web-console-2.2.1/lib/web_console/templates/_prompt_box_markup.html.erb within layouts/inlined_string (0.6ms)
Rendered /home/railsuser/.rvm/gems/ruby-2.2.2/gems/web-console-2.2.1/lib/web_console/templates/style.css.erb within layouts/inlined_string (0.7ms)
Rendered /home/railsuser/.rvm/gems/ruby-2.2.2/gems/web-console-2.2.1/lib/web_console/templates/console.js.erb within layouts/javascript (33.4ms)
Rendered /home/railsuser/.rvm/gems/ruby-2.2.2/gems/web-console-2.2.1/lib/web_console/templates/main.js.erb within layouts/javascript (0.5ms)
Rendered /home/railsuser/.rvm/gems/ruby-2.2.2/gems/web-console-2.2.1/lib/web_console/templates/error_page.js.erb within layouts/javascript (0.8ms)
Rendered /home/railsuser/.rvm/gems/ruby-2.2.2/gems/web-console-2.2.1/lib/web_console/templates/index.html.erb (67.0ms)

I can only think of there being a dependency issue based on this:
Reservation Load (0.2ms) SELECT "reservations".* FROM "reservations" WHERE "reservations"."route_id" = ? [["route_id", 10]]
Do you have any validations or restrictions on that relationship?
Also, this portion:
if #route.destroy
#route.destroy
end
redirect_to routes_url
probably should be changed to something like below if you mean to redirect based on success:
if #route.destroy
redirect_to some_other_path
else
redirect_to routes_url
end

Related

manage users by an admin in ruby on rails

how can I manage and edit other users profiles as an admin since I have one model and controller (users) ?
I tried to add a new action called updateusers
def updateusers
#other_user=User.find(params[:id])
if #other_user.update_attributes(otherusers_params)
redirect_to '/'
else
redirect_to '/manage'
end
end
the problem here :it is updating my admin user with the other_user's data
stack trace
Started GET "/manage" for ::1 at 2016-03-19 21:06:08 +0300 Processing by UsersController#manage as HTML User Load (1.0ms) SELECT "users".* FROM "users" Rendered users/manage.html.erb within layouts/application (5.0ms) User Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]] Completed 200 OK in 53ms (Views: 51.0ms | ActiveRecord: 1.0ms)
'Started GET "/users/10" for ::1 at 2016-03-19 21:06:10 +0300 Processing by UsersController#show as HTML Parameters: {"id"=>"10"} User Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 10]] Rendered users/show.html.erb within layouts/application (0.0ms) User Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]] Completed 200 OK in 37ms (Views: 36.0ms | ActiveRecord: 0.0ms)
Started GET "/editusers/10" for ::1 at 2016-03-19 21:06:11 +0300 Processing by UsersController#editusers as HTML Parameters: {"id"=>"10"} User Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 10]] Rendered users/editusers.html.erb within layouts/application (4.0ms) User Load (1.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]] Completed 200 OK in 41ms (Views: 39.0ms | ActiveRecord: 1.0ms)
Started PATCH "/users/10" for ::1 at 2016-03-19 21:06:15 +0300 Processing by UsersController#update as HTML Parameters: {"utf8"=>"✓", "authenticity_token"=>"6M1TGLQUEhiezCCg9/rT5IofdroMiQ0sm+bYcihgGDxTjDdFGU2Riou2p‌​cRk5ncjCtFDGwfBj17Uq7gc0u329w==", "user"=>{"first_name"=>"g", "last_name"=>"g", "email"=>"g#g.g", "role"=>"editor", "image"=>"pic.png", "admins"=>""}, "other"=>"update", "id"=>"10"} User Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
Unpermitted parameters: role, admins
(0.0ms) begin transaction SQL (1.0ms) UPDATE "users" SET "first_name" = ?, "last_name" = ?, "email" = ?, "updated_at" = ? WHERE "users"."id" = ? [["first_name", "g"], ["last_name", "g"], ["email", "g#g.g"], ["updated_at", "2016-03-19 18:06:15.488284"], ["id", 1]] (47.0ms) commit transaction Redirected to localhost:8080/profile Completed 302 Found in 54ms (ActiveRecord: 48.0ms)
If it's updating the wrong user, it means that params[:id] is the id of the user being updated. Are you passing the id of the user you want to update in the params? Try calling puts params.inspect at the top of the controller action to see what data is being passed. You need to look up #other_user with their id and you need to make sure that #other_user's id is being passed with the other form data.
after 10 days ,, Yes i did it - the solution is in the name of submit , I named the two submits with diffrent names <%= f.submit "update", name:"other" %>
then i used the update action like this
def update
if params[:current]
#user = current_user
if #user.update_attributes(user_params)
redirect_to '/profile'
else
redirect_to '/edit'
end
elsif params[:other]
#other_user=User.find(params[:id])
if #other_user.update_attributes(otherusers_params)
redirect_to '/'
else
redirect_to '/manage'
end
end
end

how to manage users by an admin in ruby on rails

how can I manage and edit other users profiles as an admin since I have one model and controller (users) ?
I tried to add a new action called updateusers
def updateusers
#other_user=User.find(params[:id])
if #other_user.update_attributes(otherusers_params)
redirect_to '/'
else
redirect_to '/manage'
end
end
the problem here :it is updating my admin user with the other_user's
data
stack trace
Started GET "/manage" for ::1 at 2016-03-19 21:06:08 +0300 Processing by
UsersController#manage as HTML User Load (1.0ms) SELECT "users".* FROM
"users" Rendered users/manage.html.erb within layouts/application (5.0ms) User
Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1
[["id", 1]] Completed 200 OK in 53ms (Views: 51.0ms | ActiveRecord: 1.0ms)
'Started GET "/users/10" for ::1 at 2016-03-19 21:06:10 +0300 Processing by
UsersController#show as HTML Parameters: {"id"=>"10"} User Load (0.0ms) SELECT
"users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 10]] Rendered
users/show.html.erb within layouts/application (0.0ms) User Load (0.0ms) SELECT
"users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]] Completed 200
OK in 37ms (Views: 36.0ms | ActiveRecord: 0.0ms)
Started GET "/editusers/10" for ::1 at 2016-03-19 21:06:11 +0300 Processing
by UsersController#editusers as HTML Parameters: {"id"=>"10"} User Load (0.0ms)
SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 10]]
Rendered users/editusers.html.erb within layouts/application (4.0ms) User Load
(1.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
Completed 200 OK in 41ms (Views: 39.0ms | ActiveRecord: 1.0ms)
Started PATCH "/users/10" for ::1 at 2016-03-19 21:06:15 +0300 Processing by
UsersController#update as HTML Parameters: {"utf8"=>"✓",
"authenticity_token"=>"6M1TGLQUEhiezCCg9/rT5IofdroMiQ0sm+bYcihgGDxTjDdFGU2Riou2p‌​
cRk5ncjCtFDGwfBj17Uq7gc0u329w==", "user"=>{"first_name"=>"g", "last_name"=>"g",
"email"=>"g#g.g", "role"=>"editor", "image"=>"pic.png", "admins"=>""},
"other"=>"update", "id"=>"10"} User Load (0.0ms) SELECT "users".* FROM "users"
WHERE "users"."id" = ? LIMIT 1 [["id", 1]] Unpermitted parameters: role, admins
(0.0ms) begin transaction SQL (1.0ms) UPDATE "users" SET "first_name" = ?,
"last_name" = ?, "email" = ?, "updated_at" = ? WHERE "users"."id" = ?
[["first_name", "g"], ["last_name", "g"], ["email", "g#g.g"], ["updated_at",
"2016-03-19 18:06:15.488284"], ["id", 1]] (47.0ms) commit transaction Redirected
to localhost:8080/profile Completed 302 Found in 54ms (ActiveRecord: 48.0ms)
The user ID of the form in "editusers" is set to your admin (or logged in user). It's hard to say without seeing the code but I think you've set up the editusers form incorrectly. Perhaps using a hidden field to hold the ID of the user you want to update.
Try to avoid that and set up the #user object in the 'editusers' action #user = User.find(10)
Then in your view use a form_for #user do |f| without any hidden fields for the ID.
after 10 days ,, Yes i did it - the solution is in the name of submit , I named the two submits with diffrent names <%= f.submit "update", name:"other" %> then i used the update action like this
def update
if params[:current]
#user = current_user
if #user.update_attributes(user_params)
redirect_to '/profile'
else
redirect_to '/edit'
end
elsif params[:other]
#other_user=User.find(params[:id])
if #other_user.update_attributes(otherusers_params)
redirect_to '/'
else
redirect_to '/manage'
end
end
end

How to order a collection of a habtm-association by created_at

I have three main Classes: Users, Vocabs and Tags. A User has many Tags. Tags has-and-belongs-to-many Vocabs (and the other way around).
How can I order a collection of Tags when getting them through a Vocab-Object?
#vocab.tag
gets the tags from the joins table, which has no created_at column.
Is there a handy way to solve this problem?
I am pretty new to Rails so excuse me if this is obvious.
EDIT: I just tried
#tags = #vocab.tags.order('tags.created_at DESC')
but without success.
The computer says:
Started GET "/users/1/vocabs/61" for 127.0.0.1 at 2014-12-11 15:41:15 +0100
Processing by VocabsController#show as HTML
Parameters: {"user_id"=>"1", "id"=>"61"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
Vocab Load (0.3ms) SELECT "vocabs".* FROM "vocabs" WHERE "vocabs"."user_id" = ? AND "vocabs"."id"
= ? ORDER BY created_at DESC LIMIT 1 [["user_id", 1], ["id", 61]]
Tag Load (0.5ms) SELECT DISTINCT "tags".* FROM "tags" INNER JOIN "tags_vocabs" ON "tags"."id" =
"tags_vocabs"."tag_id" WHERE "tags_vocabs"."vocab_id" = ? [["vocab_id", 61]]
Rendered shared/_error_messages.html.erb (0.2ms)
Rendered vocabs/show.html.erb within layouts/application (10.7ms)
Rendered layouts/_shim.html.erb (0.1ms)
Rendered layouts/_header.html.erb (1.1ms)
Completed 200 OK in 602ms (Views: 587.3ms | ActiveRecord: 1.2ms)
The controller action looks like this:
def new_tag
#user = current_user
#vocab = #user.vocabs.find(params[:id])
#tags = #vocab.tags.order('tags.created_at DESC')
#tag = current_user.tags.build(name: params[:tag])
if #tag.save
#vocab.tags<<#tag
flash.now[:success] ='Tag successfully created.'
redirect_to user_vocab_path(#user, #vocab)
else
flash.now[:danger] = "Tag could not be created!"
render :action => "show"
end
end

Render does not work after call to update function in Rails

My controller's update function looks like this:
def update
#cohort = Cohort.find(params[:cohort][:id])
#cohort.update_attributes(params[:cohort])
respond_to do |format|
format.js {render action: "show", layout: "courses"}
end
end
When I trigger the update function (via js), get the following in my Rails console:
Started PUT "/cohorts/41" for 127.0.0.1 at 2014-07-18 21:57:26 -0400
Processing by CohortsController#update as */*
Parameters: {"cohort"=>{"id"=>"41", "user_id"=>"17", "room_id"=>"16"}, "id"=>"41"}
Cohort Load (0.1ms) SELECT "cohorts".* FROM "cohorts" WHERE "cohorts"."id" = ? LIMIT 1 [["id", "41"]]
(0.0ms) begin transaction
(0.3ms) UPDATE "cohorts" SET "room_id" = 16, "updated_at" = '2014-07-18 21:57:26.303928' WHERE "cohorts"."id" = 41
(8.5ms) commit transaction
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = 17 LIMIT 1
Course Load (0.1ms) SELECT "courses".* FROM "courses" WHERE "courses"."id" = 21 LIMIT 1
Timeperiod Load (0.1ms) SELECT "timeperiods".* FROM "timeperiods" WHERE "timeperiods"."id" = 37 LIMIT 1
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = 17 LIMIT 1
User Load (0.2ms) SELECT "users".* FROM "users" WHERE (role = 'faculty' OR role = 'admin')
FacultyReport Load (0.1ms) SELECT "faculty_reports".* FROM "faculty_reports" WHERE "faculty_reports"."cohort_id" = 41 LIMIT 1
Room Load (0.1ms) SELECT "rooms".* FROM "rooms"
Room Load (0.1ms) SELECT "rooms".* FROM "rooms" WHERE "rooms"."id" = 16 LIMIT 1
Enrollment Load (0.1ms) SELECT "enrollments".* FROM "enrollments" WHERE "enrollments"."cohort_id" = 41
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = 17 LIMIT 1
Rendered cohorts/show.html.erb within layouts/courses (12.3ms)
Rendered layouts/_header.html.erb (2.1ms)
Rendered layouts/_leftnav.html.erb (0.8ms)
Rendered layouts/_messages.html.erb (0.1ms)
Completed 200 OK in 44.7ms (Views: 31.1ms | ActiveRecord: 10.0ms)
Notice it says Rendered cohorts/show.html.erb within layouts/courses (12.3ms). In the browser itself, no refresh or re-rendering occurs. If I manually refresh the page, I can see the changes were made but the page itself change.
Also, if I change render to redirect_to I get (in the console) a redirect loop that goes for about 14 iterations and then stops and no changes in the browser.
respond_to
From your comments & looking at your code, you need to remember how Rails repond_to block works
When you call format.js, Rails will automatically look for [action_name].js.erb in your views/controller folder. This file will essentially run when you hit the update action from ajax / JS, it will perform the function & then look for update.js.erb to run.
You have several issues with your code:
#app/controllers/your_controller.rb
Class YourController < ApplicationController
def update
#cohort = Cohort.find(params[:cohort][:id])
#cohort.update_attributes(params[:cohort])
respond_to do |format|
format.js {render layout: "courses"} #-> automatically loads views/your_controller/update.js.erb
end
end
end
--
Update
Something else you should consider is your update functionality - specifically that you're trying to update a model with naked params (you should use strong_params):
def update
#cohort = Cohort.find params[:cohort][:id]
#cohort.update(cohort_params)
end
private
def cohort_params
params.require(:cohort).permit(:your, :params)
end
Edit:
I changed format.js {render action: "show", layout: "courses"} to format.js {render "update.js.erb"} and it works as intended.

JS Request getting called twice in a row

I'm working on the Ruby on Rails Tutorial. I have the asynchronous follow buttons working. Interestingly, each of the javascript calls is getting called twice in a row when I click the button. Any thoughts on how I make it only send one request? Here is my log
Started POST "/tag_user_relationships/123" for
127.0.0.1 at 2011-06-13 21:18:59 -0700 Processing by TagUserRelationshipsController#destroy as JS Parameters: {"utf8"=>"✓", "authenticity_token"=>"goedvibRxKtDRiAufp1ThWJP0rRBU2cMH2xp7qodKws=", "commit"=>"Unfollow", "id"=>"123"} User Load (0.2ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 2 LIMIT 1 TagUserRelationship Load (0.2ms) SELECT `tag_user_relationships`.* FROM `tag_user_relationships` WHERE `tag_user_relationships`.`id` = 123 LIMIT 1 Tag Load (0.2ms) SELECT `tags`.* FROM `tags` WHERE `tags`.`id`
= 9 LIMIT 1 TagUserRelationship Load (0.3ms) SELECT `tag_user_relationships`.* FROM `tag_user_relationships` WHERE `tag_user_relationships`.`tag_id` = 9 AND (`tag_user_relationships`.user_id
= 2) LIMIT 1 SQL (0.1ms) BEGIN AREL (0.2ms) DELETE FROM `tag_user_relationships` WHERE `tag_user_relationships`.`id` = 123 SQL (0.4ms) COMMIT SQL (0.4ms) SELECT COUNT(*) FROM `users` INNER JOIN `tag_user_relationships` ON `users`.id = `tag_user_relationships`.user_id WHERE ((`tag_user_relationships`.tag_id = 9)) SQL (0.3ms) SELECT COUNT(*) FROM `tags` INNER JOIN `tag_user_relationships` ON `tags`.id
= `tag_user_relationships`.tag_id WHERE ((`tag_user_relationships`.user_id = 2)) Rendered tag_user_relationships/_form.js.erb (15.8ms) Rendered tags/_follow.html.erb (2.1ms) Rendered tag_user_relationships/destroy.js.erb (20.3ms) Completed 200 OK in 138ms (Views: 28.1ms | ActiveRecord: 2.3ms)
Started POST "/tag_user_relationships/123" for
127.0.0.1 at 2011-06-13 21:18:59 -0700 Processing by TagUserRelationshipsController#destroy as JS Parameters: {"utf8"=>"✓", "authenticity_token"=>"goedvibRxKtDRiAufp1ThWJP0rRBU2cMH2xp7qodKws=", "id"=>"123"} User Load (0.2ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 2 LIMIT 1 TagUserRelationship Load (0.2ms) SELECT `tag_user_relationships`.* FROM `tag_user_relationships` WHERE `tag_user_relationships`.`id` = 123 LIMIT 1 Completed 404 Not Found in 70ms
ActiveRecord::RecordNotFound (Couldn't find TagUserRelationship with ID=123): app/controllers/tag_user_relationships_controller.rb:14:in `destroy'
Rendered /Users/me/.rvm/gems/ruby-1.9.2-p136#rails3tutorial/gems/actionpack-3.0.8/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.0ms) Rendered /Users/me/.rvm/gems/ruby-1.9.2-p136#rails3tutorial/gems/actionpack-3.0.8/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (153.6ms) Rendered /Users/me/.rvm/gems/ruby-1.9.2-p136#rails3tutorial/gems/actionpack-3.0.8/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (160.2ms)
And here is my view
$("#<%= "follower_info#{#tag.id}" %>").html("<%=escape_javascript(pluralize(#tag.followers.count,'follower'))%>");
var link = $('<a>').attr('href',"<%=user_tags_path(current_user) %>").text("<%= escape_javascript(pluralize(current_user.beats.count,'tag')) %>");
$("#<%= "user#{current_user.id}_following" %>").html(link); $("#<%= "follow_form#{#tag.id}" %>").html("<%= escape_javascript("#{render('tags/unfollow', :tag => #tag)}").html_safe %>");
And my controller
def create
#tag = Tag.find(params[:tag_user_relationship][:tag_id])
current_user.follow_tag!(#tag)
respond_to do |format|
format.html { redirect_to #tag }
format.js
end
end
I had this same issue recently. Is there any chance that you installed the ajax gem and also included the jquery code in the Javascripts folder? If so, the calls will be made twice.

Resources