Render does not work after call to update function in Rails - ruby-on-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.

Related

ActiveRecord::RecordNotDestroyed

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

Having trouble with create method in CommentsController

This is my current Create method in CommentsController
def create
#place = Place.find(params[:place_id])
#comment = #place.comments.create(comment_params)
#comment.user = current_user
if #comment.save
redirect_to place_path(#place)
else
render "comments/_form"
end
end
I was told by someone that this hits the database twice. Upon checking the logs, this is the result:
Started GET "/places/9" for 127.0.0.1 at 2015-01-22 15:01:47 -0800
Processing by PlacesController#show as HTML
Parameters: {"id"=>"9"}
Place Load (0.3ms) SELECT "places".* FROM "places" WHERE "places"."id" = ? LIMIT 1 [["id", 9]]
Comment Load (0.2ms) SELECT "comments".* FROM "comments" WHERE "comments"."place_id" = ? [["place_id", 9]]
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 2]]
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 2]]
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 2]]
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 2]]
Rendered comments/_comment.html.erb (8.0ms)
Rendered comments/_form.html.erb (2.7ms)
Rendered places/show.html.erb within layouts/application (73.3ms)
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 2]]
Completed 200 OK in 532ms (Views: 529.4ms | ActiveRecord: 1.0ms)
So obviously, I don't want to be inefficient in my code.
This is what the person suggested instead:
comment_params[:user_id] = current_user.id
if #places.comments.create(comment_params)
.....
else
....
end
So ... I rewrote the Create method to this:
def create
#place = Place.find(params[:place_id])
#comment = #place.comments.create(comment_params)
comment_params[:user_id] = current_user.id
if #places.comments.create(comment_params)
redirect_to place_path(#place)
else
render "comments/_form"
end
end
Upon the rewritten Create method, I keep getting this error when I try to leave a comment: undefined method comments for nil:NilClass
Help me to understand how to rewrite this Create method correctly, please?
SideNote - Not sure if it's relevant if yes, please address it, if no, please ignore
Upon checking the last comment in the rails console, I was startled to see that the user_id is nil, whereas for place, it's not.
Place belongs to User
Comment belongs to User
User has many of both Place and Comment
You're calling create twice, which would result in the comment being posted twice, which is probably not what you have intended.
The first time you call create, it has no user_id assigned, that's the reason the user_id is set to null in the database (hint: use a presence validation on the user_id in your comment model).
The second time you call create you call it on #places instead of #place (typo). This causes your nil error.
Here is another way to solve your problem:
def create
#place = Place.find(params[:place_id])
#comment = #place.comments.build(comment_params)
#comment.user_id = current_user.id
if #comment.save(comment_params)
redirect_to place_path(#place)
else
render "comments/_form"
end
end
The difference is, that we first "build" a comment without creating it, but it will be filled with the ID of the place etc.
In a next step we add the current user's id and then we call save on the object, which hits the database.

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

Seems like Rails do caching, which I don't want it to

There is #avalibable_colors=['#5A009D', '#004DFF', '#F4F400', '#FF8000'] variable (it is not instance of model), which represent avaliable options - colors, which hadn't been taken yet, through method:
def choose_color
#check=Check.find(params[:check_id])
#colorschemes=#check.colorschemes
current_colors=[]
#check.colorschemes.each do |c|
current_colors.push(c.color)
end
#avalibable_colors=['#5A009D', '#004DFF', '#F4F400', '#FF8000']
current_colors.each do |c|
if #avalibable_colors.index(c)
#avalibable_colors[#avalibable_colors.index(c)]=nil
end
end
#avalibable_colors.compact!
respond_to do |format|
format.js
end
end
After that #avalibable_colors contents only untaken color options.
And generally it works. If I choose 1 color option, it displays rest 4, if 2 - rest 3, if I choose one, and then delete it - it is in avaliable colors.
And that works until whole four. And If I add all four, and then delete one by one, no colors are avaliable until I refresh page.
Server logs:
Started GET "/choose_color?check_id=46" for 127.0.0.1 at 2013-06-13 19:00:31 +0400
Processing by ColorschemesController#choose_color as JS
Parameters: {"check_id"=>"46"}
User Load (1.0ms) SELECT "users".* FROM "users" WHERE "users"."auth_token" = 'oPXJtztDkYdYmVsQ3wxxfQ' LIMIT 1
Check Load (1.0ms) SELECT "checks".* FROM "checks" WHERE "checks"."id" = 46 LIMIT 1
CACHE (0.0ms) SELECT "checks".* FROM "checks" WHERE "checks"."id" = 46 LIMIT 1
Check Load (1.0ms) SELECT "checks".* FROM "checks" WHERE "checks"."id" = $1 LIMIT 1 [["id", "46"]]
Colorscheme Load (0.0ms) SELECT "colorschemes".* FROM "colorschemes" WHERE "colorschemes"."check_id" = 46
Rendered colorschemes/_choose_color.html.erb (0.0ms)
Rendered colorschemes/choose_color.js.erb (5.0ms)
Completed 200 OK in 33ms (Views: 22.0ms | ActiveRecord: 3.0ms)

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