Every link_to on my rails 4 application is being called twice - ruby-on-rails

I'm experiencing some unusual behaviour with my Rails 4 Application. Every single-time I click on a link_to inside my views, my controllers actions are being called twice. For example:
In my root_url I have this standard call for users_profile:
<%= link_to('User Profile', users_profile_path, :class => "logout-button") %>
When I click this link, my console shows the following output:
Started GET "/users/profile" for 127.0.0.1 at 2013-11-25 20:45:53 -0200
Processing by Users::SessionsController#profile as HTML
User Load (0.7ms) SELECT "users".* FROM "users" WHERE "users"."id" = 45 ORDER BY "users"."id" ASC LIMIT 1
InvestorProfile Load (0.5ms) SELECT "investor_profiles".* FROM "investor_profiles" WHERE "investor_profiles"."user_id" = $1 ORDER BY "investor_profiles"."id" ASC LIMIT 1 [["user_id", 45]]
EmployeeProfile Load (0.5ms) SELECT "employee_profiles".* FROM "employee_profiles" WHERE "employee_profiles"."user_id" = $1 ORDER BY "employee_profiles"."id" ASC LIMIT 1 [["user_id", 45]]
Rendered users/sessions/_investor_setup.html.erb (3.9ms)
Rendered users/sessions/profile.html.erb within layouts/application (5.2ms)
Completed 200 OK in 19ms (Views: 11.2ms | ActiveRecord: 2.5ms)
Started GET "/users/profile" for 127.0.0.1 at 2013-11-25 20:45:53 -0200
Processing by Users::SessionsController#profile as HTML
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = 45 ORDER BY "users"."id" ASC LIMIT 1
InvestorProfile Load (0.3ms) SELECT "investor_profiles".* FROM "investor_profiles" WHERE "investor_profiles"."user_id" = $1 ORDER BY "investor_profiles"."id" ASC LIMIT 1 [["user_id", 45]]
EmployeeProfile Load (0.2ms) SELECT "employee_profiles".* FROM "employee_profiles" WHERE "employee_profiles"."user_id" = $1 ORDER BY "employee_profiles"."id" ASC LIMIT 1 [["user_id", 45]]
Rendered users/sessions/_investor_setup.html.erb (3.3ms)
Rendered users/sessions/profile.html.erb within layouts/application (4.1ms)
Completed 200 OK in 12ms (Views: 7.5ms | ActiveRecord: 1.2ms)
People often have this behaviour when there's a remote (JS for example) calling the method, but this is not my case. the weirdest part is that, if I put the direct URL to the users_profile_path on my browser. I only get one request on my rails console:
Started GET "/users/profile" for 127.0.0.1 at 2013-11-25 20:48:17 -0200
Processing by Users::SessionsController#profile as HTML
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = 45 ORDER BY "users"."id" ASC LIMIT 1
InvestorProfile Load (0.3ms) SELECT "investor_profiles".* FROM "investor_profiles" WHERE "investor_profiles"."user_id" = $1 ORDER BY "investor_profiles"."id" ASC LIMIT 1 [["user_id", 45]]
EmployeeProfile Load (0.2ms) SELECT "employee_profiles".* FROM "employee_profiles" WHERE "employee_profiles"."user_id" = $1 ORDER BY "employee_profiles"."id" ASC LIMIT 1 [["user_id", 45]]
Rendered users/sessions/_investor_setup.html.erb (3.4ms)
Rendered users/sessions/profile.html.erb within layouts/application (4.2ms)
Completed 200 OK in 12ms (Views: 7.7ms | ActiveRecord: 1.1ms)
I'm getting this same result for every link inside my application, not only this one.

Rails 5/6
When I was clicking on a link, the whole controller was being called twice. I tried the accepted answer, but it does not work for me, so I just set turbolinks: false as below:
<%= link_to("Demo", #user, data: { turbolinks: false } ) %>

If you would like your app to still make use of Turbolinks then "Opting out of Turbolinks" on the code that is giving you problems is the way to go; just add data-no-turbolink.
I was having problems with using Bootstrap 3 and adding that fixed it. For example;
<li class="list-group-item" data-no-turbolink>
<%= link_to download_path(item) do %>
<button type="button" class="btn btn-success">Download</button>
<% end %>
</li>

I actually managed to solve this on my own.
There's a default gem that is installed with rails 4.0, it is called Turbolinks*.
For some reason, the javascript used in this gem* was causing the doubled requests on my server. That's why only GET requests were behaving like this, and POST requests were normal.
I still don't fully understand why gem* causes that, but after I removed the following line from my application.js file, the doubled requests stopped.
=// require turbolinks

Another solution is to add data-no-turbolink to the tag.
More info here: http://blog.flightswithfriends.com/post/53943440505/how-to-disable-turbolinks-in-rails-4

Related

Why is my rails app showing a blank page?

I am going though Michael Hartl's rails Tutorial chapter 10 section 10.2. And my rails app is now showing a blank page for all pages I try to load on the local host. I have tried resetting the computer as suggested in another post, but this didn't work. I have checked the development log and here is the error message.
Started GET "/users/3" for 95.10.6.124 at 2017-11-05 16:36:43 +0000
Cannot render console from 95.10.6.124! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by UsersController#show as HTML
Parameters: {"id"=>"3"}
[1m[36mUser Load (0.2ms)[0m [1m[34mSELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?[0m [["id", 3], ["LIMIT", 1]]
Rendering users/show.html.erb within layouts/application
Rendered users/show.html.erb within layouts/application (1.7ms)
Rendered layouts/_rails_default.html.erb (27.1ms)
Rendered layouts/_shim.html.erb (0.5ms)
[1m[36mUser Load (0.2ms)[0m [1m[34mSELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?[0m [["id", 3], ["LIMIT", 1]]
Rendered layouts/_header.html.erb (2.3ms)
Rendered layouts/_footer.html.erb (0.5ms)
Completed 200 OK in 41ms (Views: 38.0ms | ActiveRecord: 0.4ms)
This is strange as I undid the changes I made and now it doesnt work. In fact the serve doesnt seem to start. Instead of seeing the usual "ctrl+c to stop" at the end, the command prompt appears. This hasnt happened before and to my mnowledge I havent done anything differently.
Could someone help me with this, thanks.

ruby on rails -- Couldn't find User with 'id'=

I am creating a blog and I want to show profile containing all posts of a perticular user by clicking the "uploader" link in index.html.erb(line no. 9). I used a controller named Pages and defined profile in it and linked it to "uploader" and passed user of that post.
code screenshot
I am getting error "Couldn't find User with 'id'="
error screenshot
terminal is showing User id as nil
Started GET "/" for 127.0.0.1 at 2017-03-27 02:08:49 +0530
Processing by PostsController#index as HTML
Post Load (0.5ms) SELECT "posts".* FROM "posts" ORDER BY created_at DESC
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 4]]
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 3]]
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 2]]
Rendered posts/index.html.erb within layouts/application (10.8ms)
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 3]]
Completed 200 OK in 84ms (Views: 81.4ms | ActiveRecord: 1.1ms)
Started GET "/pages/profile.3" for 127.0.0.1 at 2017-03-27 01:49:02 +0530
Processing by PagesController#profile as
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", nil]]
Completed 404 Not Found in 1ms (ActiveRecord: 0.1ms)
ActiveRecord::RecordNotFound (Couldn't find User with 'id'=):
app/controllers/pages_controller.rb:3:in `profile'
What am I doing wrong?
Any better method to do this?
Your problem is the route. This:
GET "/pages/profile.3"
should really be this:
GET "/pages/profile/3"
and that's caused by your route missing the required parameter. Change it to
# routes.rb
get 'pages/profile/:id
and it should work.

Rails 4 - Can't update model attribute

How can I save an attribute based on a condition between attributes of the same model? I've been unable to update a record unless the attribute's state remains the true.
I've checked this thread before: Rails. Update model attributes on save
This is the code I'm running:
class Ip < ActiveRecord::Base
has_paper_trail
has_and_belongs_to_many :users
validates_uniqueness_of :ip_address, :hostname
before_save :set_availability
extend Enumerize
enumerize :status, in: [:available, :allocated, :pending, :blocked], default: :available
def ip_address_name
self.ip_address
end
def set_availability
self.is_available = false unless self.status.available?
end
end
Basically I have a list of "Ips" which I'd like to keep track of, and a "is_available" boolean to tell me wether the ip's status is available or not (which should set itself automatically, based on the "status" field).
So the issue is, for example,
I access the model, edit the record, change the :status from :available to :allocated, and hit "Save", it rolls back, raises me "Ip failed to be updated", and on the server the transaction is "Completed 406 Not Acceptable"
Here's the log:
=============== Phusion Passenger Standalone web server started ===============
PID file: /home/user/IP_Manager/tmp/pids/passenger.3000.pid
Log file: /home/user/IP_Manager/log/passenger.3000.log
Environment: development
Accessible via: http://0.0.0.0:3000/
You can stop Phusion Passenger Standalone by pressing Ctrl-C.
Problems? Check https://www.phusionpassenger.com/library/admin/standalone/troubleshooting/
===============================================================================
App 31353 stdout:
App 31368 stdout:
Started HEAD "/" for 127.0.0.1 at 2015-08-04 09:41:07 -0300
ActiveRecord::SchemaMigration Load (0.2ms) SELECT "schema_migrations".* FROM "schema_migrations"
Processing by HomeController#index as HTML
Redirected to http://0.0.0.0/users/sign_in
Completed 302 Found in 10ms (ActiveRecord: 0.0ms)
Started GET "/admin/ip/2/edit" for 127.0.0.1 at 2015-08-04 09:41:14 -0300
Processing by RailsAdmin::MainController#edit as HTML
Parameters: {"model_name"=>"ip", "id"=>"2"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]]
Ip Load (0.1ms) SELECT "ips".* FROM "ips" WHERE "ips"."id" = ? ORDER BY "ips"."id" ASC LIMIT 1 [["id", 2]]
Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/rails_admin/main/_form_boolean.html.haml (2.4ms)
Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/rails_admin/main/_form_field.html.haml (1.2ms)
Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/rails_admin/main/_form_field.html.haml (0.2ms)
Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/rails_admin/main/_form_enumeration.html.haml (2.7ms)
Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/rails_admin/main/_form_text.html.haml (1.0ms)
User Load (0.2ms) SELECT "users".* FROM "users" INNER JOIN "ips_users" ON "users"."id" = "ips_users"."user_id" WHERE "ips_users"."ip_id" = ? [["ip_id", 2]]
(0.1ms) SELECT COUNT(*) FROM "users"
User Load (0.1ms) SELECT "users".* FROM "users" ORDER BY users.id desc
Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/rails_admin/main/_form_filtering_multiselect.html.haml (27.7ms)
Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/rails_admin/main/_submit_buttons.html.haml (2.8ms)
Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/rails_admin/main/edit.html.haml within layouts/rails_admin/application (64.5ms)
Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/layouts/rails_admin/_secondary_navigation.html.haml (3.7ms)
Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/layouts/rails_admin/_navigation.html.haml (6.6ms)
Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/layouts/rails_admin/_sidebar_navigation.html.haml (4.1ms)
Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/layouts/rails_admin/pjax.html.haml (7.3ms)
Completed 200 OK in 611ms (Views: 484.5ms | ActiveRecord: 1.6ms)
Started PUT "/admin/ip/2/edit" for 127.0.0.1 at 2015-08-04 09:41:20 -0300
Processing by RailsAdmin::MainController#edit as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"OI5LqfNXeYLQm1wGglmnPvkrTL3sHTYsiE/uJGp7Uxuserk7ee8b8ozIXclBkUtYYcoIeKCjcNnyZ00siruQjEZQ==", "ip"=>{"is_available"=>"1", "ip_address"=>"192.168.0.2", "hostname"=>"localhost2", "status"=>"allocated", "details"=>"", "user_ids"=>["", "", "1"]}, "return_to"=>"", "_save"=>"", "model_name"=>"ip", "id"=>"2"}
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]]
Ip Load (0.1ms) SELECT "ips".* FROM "ips" WHERE "ips"."id" = ? ORDER BY "ips"."id" ASC LIMIT 1 [["id", 2]]
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
User Load (0.1ms) SELECT "users".* FROM "users" INNER JOIN "ips_users" ON "users"."id" = "ips_users"."user_id" WHERE "ips_users"."ip_id" = ? [["ip_id", 2]]
(1.1ms) begin transaction
Ip Exists (0.2ms) SELECT 1 AS one FROM "ips" WHERE ("ips"."ip_address" = '192.168.0.2' AND "ips"."id" != 2) LIMIT 1
Ip Exists (0.2ms) SELECT 1 AS one FROM "ips" WHERE ("ips"."hostname" = 'localhost2' AND "ips"."id" != 2) LIMIT 1
(0.1ms) rollback transaction
PaperTrail::Version Load (0.3ms) SELECT "versions".* FROM "versions" WHERE "versions"."item_id" = ? AND "versions"."item_type" = ? ORDER BY "versions"."created_at" ASC, "versions"."id" ASC [["item_id", 2], ["item_type", "Ip"]]
Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/rails_admin/main/_form_boolean.html.haml (0.4ms)
Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/rails_admin/main/_form_field.html.haml (0.4ms)
Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/rails_admin/main/_form_field.html.haml (0.3ms)
Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/rails_admin/main/_form_enumeration.html.haml (1.1ms)
Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/rails_admin/main/_form_text.html.haml (0.5ms)
User Load (0.2ms) SELECT "users".* FROM "users" ORDER BY users.id desc
Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/rails_admin/main/_form_filtering_multiselect.html.haml (5.0ms)
Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/rails_admin/main/_submit_buttons.html.haml (1.5ms)
Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/rails_admin/main/edit.html.haml within layouts/rails_admin/application (25.7ms)
Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/layouts/rails_admin/_secondary_navigation.html.haml (1.9ms)
Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/layouts/rails_admin/_navigation.html.haml (3.6ms)
Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/layouts/rails_admin/_sidebar_navigation.html.haml (2.6ms)
Rendered /home/user/.rvm/gems/ruby-2.2.1/gems/rails_admin-0.6.8/app/views/layouts/rails_admin/pjax.html.haml (6.1ms)
Completed 406 Not Acceptable in 267ms (Views: 223.5ms | ActiveRecord: 2.9ms)
This is my Gemfile (only the extra gems besides the default ones):
# Administration Panel Gems
gem 'rails_admin' # Rails Administration Panel Gem
gem 'rails_admin_history_rollback' # Enables users to visualise and revert history
gem 'rails_admin_import', "~> 1.0.0" # Enables importation
gem 'devise' # Authentication Gem
gem 'cancancan' # Authorization Gem
gem 'paper_trail', '~> 4.0.0.rc' # Auditing Gem (History)
gem 'enumerize' # Gem for enumerizing attributes
# Server gem
gem 'passenger'
Thank you for your time!
Not sure if that's what is causing the issue, but it might. If any method executed as before_save returns false, the whole transaction is aborted.
Your method:
def set_availability
self.is_available = false unless self.status.available?
end
will return false or nil. First case will cancel transaction. Change this method to:
def set_availability
self.is_available = false unless self.status.available?
true
end
Since you're setting a false value inside of set_availability, a false value gets returned from the callback and it rolls back. A before* callback that returns false will rollback all updates on the model.
From the Rails docs http://guides.rubyonrails.org/active_record_callbacks.html
6 Halting Execution
As you start registering new callbacks for your models, they will be
queued for execution. This queue will include all your model's
validations, the registered callbacks, and the database operation to
be executed.
The whole callback chain is wrapped in a transaction. If any before
callback method returns exactly false or raises an exception, the
execution chain gets halted and a ROLLBACK is issued; after callbacks
can only accomplish that by raising an exception.
Something like this might work.
def set_availability
self.is_available = false unless self.status.available?
true
end

Ruby on Rails send_file, code in controller action running twice

I'm running into a weird issue with user downloadable files, the file is downloading properly, but other code in the controller action is executing twice. I'm using CarrierWave, which is mounted on a Document model at .file.
I want users to be able to click this link to download the file:
<%= link_to document.file.file.filename, document_path(document) %>
This is what my controller looks like:
def show
document = Document.find(params[:id])
# Track this download
CourseDownload.create(course: document.course, user: current_user)
# Download the file
send_file 'public' + document.file.url.to_s
end
When I click the link, the file downloads, but 2 CourseDownload records are created. In the logs it looks like the GET request is happening twice:
Started GET "/documents/1" for 127.0.0.1 at 2014-04-17 18:12:47 -0400
Processing by DocumentsController#show as HTML
Parameters: {"id"=>"1"}
Document Load (0.2ms) SELECT "documents".* FROM "documents" WHERE "documents"."id" = ? LIMIT 1 [["id", "1"]]
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."remember_token" = 'xxx' LIMIT 1
CACHE (0.0ms) SELECT "documents".* FROM "documents" WHERE "documents"."id" = ? LIMIT 1 [["id", "1"]]
public/uploads/document/file/1/bootstrap-3.0.0.zip
Sent file public/uploads/document/file/1/bootstrap-3.0.0.zip (0.1ms)
Completed 200 OK in 7ms (ActiveRecord: 0.4ms)
Started GET "/documents/1" for 127.0.0.1 at 2014-04-17 18:12:47 -0400
Processing by DocumentsController#show as HTML
Parameters: {"id"=>"1"}
Document Load (0.2ms) SELECT "documents".* FROM "documents" WHERE "documents"."id" = ? LIMIT 1 [["id", "1"]]
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."remember_token" = 'xxx' LIMIT 1
CACHE (0.0ms) SELECT "documents".* FROM "documents" WHERE "documents"."id" = ? LIMIT 1 [["id", "1"]]
public/uploads/document/file/1/bootstrap-3.0.0.zip
Sent file public/uploads/document/file/1/bootstrap-3.0.0.zip (0.1ms)
Completed 200 OK in 5ms (ActiveRecord: 0.3ms)
Any idea what I'm doing wrong?
Thanks!
The issue ended up being caused by a turbolinks gotcha.
Resolved with:
<%= link_to document.file.file.filename, document_path(document), 'data-no-turbolink' => true %>

Github-like username url

I have this route that let me build custom url for users like
/thisismyname, and it works fine. But when I look at the log there is
something I don't like...
When I hit /gregory this is what is happenning:
1. Going to public_profile#public # Good
2. hitting /assets and trying to find a user with asset token # Not good
I thought my constraints would avoid this but it doesn't seem like it...
class PublicProfileConstraint
def self.matches?(request)
!['assets', 'admin'].include?(request.session[:token])
end
end
get "/:token" => "profiles#public", :as => :public_profile,
:constraints => PublicProfileConstraint
Here is the log:
Started GET "/gregory" for 127.0.0.1 at 2012-03-05 12:44:43 -0800
Processing by ProfilesController#public as HTML
Parameters: {"token"=>"gregory"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE
"users"."id" = ? LIMIT 1 [["id", 1]]
User Load (0.3ms) SELECT "users".* FROM "users" WHERE
"users"."token" = 'gregorymarcilhacy' LIMIT 1
Rendered profiles/_modal.haml (0.1ms)
....
Rendered profiles/show.haml within layouts/application (154.7ms)
Completed 200 OK in 431ms (Views: 174.0ms | ActiveRecord: 5.5ms)
... Redering js files ...
# I DONT WANT THIS
Started GET "/assets/" for 127.0.0.1 at 2012-03-05 12:44:45 -0800
Served asset - 404 Not Found (10ms)
Processing by ProfilesController#public as */*
Parameters: {"token"=>"assets"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE
"users"."id" = ? LIMIT 1 [["id", 1]]
User Load (0.3ms) SELECT "users".* FROM "users" WHERE
"users"."token" = 'assets' LIMIT 1
Redirected to http://localhost:3000/
Completed 302 Found in 312ms
... Rendering images ...
# AND I DONT WANT THIS
Started GET "/" for 127.0.0.1 at 2012-03-05 12:44:45 -0800
Processing by LandingController#landing as */*
User Load (0.3ms) SELECT "users".* FROM "users" WHERE
"users"."id" = ? LIMIT 1 [["id", 1]]
Rendered landing/landing.haml within layouts/landing (0.8ms)
Completed 200 OK in 288ms (Views: 23.5ms | ActiveRecord: 2.2ms)
You are searching request.session for the token, but this will always fail as that's the session store rather than the request parameters. You probably want the equivalent of params[:token] in the constraint class. The request object documentation indicates that request.path_parameters[:token] might contain the value you are looking for.

Resources