Rails strange behavior of production app running on heroku - ruby-on-rails

In user model I've got attribute location of type point. Now I've got a validation code:
validates :location, :format => { :with => /\(-?\d+(?:\.\d+)?,-?\d(?:\.\d+)?\)/,
:on => :update,
:if => :location_changed? }
It works fine in console, on localhost, but on heroku it returns:
Processing by UsersController#update as / 2012-07-31T18:14:37+00:00
app[web.1]: Parameters:
{"user"=>{"location"=>"(3.545452,2.4353534)"}, "id"=>"self"}
2012-07-31T18:14:37+00:00 app[web.1]: Completed 500 Internal Server
Error in 13ms 2012-07-31T18:14:37+00:00 app[web.1]:
2012-07-31T18:14:37+00:00 app[web.1]: NoMethodError (undefined method
location_changed?' for #<User:0x00000004dc29c8>):
2012-07-31T18:14:37+00:00 app[web.1]:
app/controllers/users_controller.rb:16:inupdate'
Actually it works also great in heroku console, but don't work in curl request.
Rails version 3.2.7.
attr_accessible :profile_picture, :password, :location
Thanks!

It looks like a magic. I fixed it with recreation if table and server restart. Very strange.

Related

Why do I get an InvalidSignature error when uploading multiple images?

I'm new to Rails and I'm trying to save multiple images that come from the front end using a Rails API. I did the ActiveStorage migration but it still gives me the error.
Error:
ActiveSupport: :MessageVerifier::InvalidSignature (ActiveSupport: :MessageVerifier: :InvalidSignature):
app/controllers/posts_controller.rb:20:in ‘create'
Started POST "“/posts" for 172.19.0.1 at 2021-08-05 11:28:13 +0000
Processing by PostsController#create as HTML
Parameters: {"post"=>{"type_id"=>"1", "title"=>"test", "location"=>"calmo", "“category"=>"New Company", "“description"=>"", “images"=>["[object File],[object File],[object File],[
object File]"], "“start_date"=>"2010-03-02", "“end_date"=>"2011-03-02", "“start_time"=>"14:50", "end_time"=>"14:53"}}
User Load (1.0ms) [{"id", 3], ["LIMIT", 1]]
Completed 500 Internal Server Error in 21ms (ActiveRecord: 8.0ms | Allocations: 3822)
server side error
Post.rb
class Post < ApplicationRecord
belongs_to :user
has_many_attached :images
end
posts_controller.rb
def post_params
params.require(:post).permit(:type_id, :category, :title, :location, :description,
:start_date, :end_date, :start_time, :end_time, images: [])
end
index.js
const handleSubmit = (event) => {
event.preventDefault();
const formData = new FormData();
formData.append('post[type_id]', data.type);
formData.append('post[title]', data.title);
formData.append('post[location]', data.location);
formData.append('post[category]', data.category);
formData.append('post[description]', data.description);
formData.append('post[images][]', data.images);
formData.append('post[start_date]', data.startDate);
formData.append('post[end_date]', data.endDate);
formData.append('post[start_time]', data.startTime);
formData.append('post[end_time]', data.endTime);
post(formData, '/posts', function (response) {
alert(response.data);
});
};
Might be a bit late but I had the same problem today and came across this post. Later I figured it out. I did a loop through the images.
Like you, I had like this (using your code above as an example):
formData.append('post[images][]', data.images);
And I kept getting the InvalidSignature error from Rails 7. Then I decided to do a loop:
for (let i = 0; i < data.images.length; i++) {
formData.append('post[images][]', data.images[i]);
}
and the problem was solved for me.

Unexpected = in haml file after updating Ruby

I am running a rails application (rails: 4.2 and ruby 2.2.3). I am trying to update my ruby to 2.4.4 and have been able to successfully run bundle install. However, when I start the server and go to the home page of my application, I encounter a unexpected = in the application.html.haml file for this line:
= favicon_link_tag 'favicon.ico'
Has anyone here encountered an error like this?
P.S. if this question has been posted before can someone redirect me to it as I cannot find this problem.
%head
%base{:href => "/dashboard"}
%title Title Page
= favicon_link_tag 'favicon.ico'
= stylesheet_link_tag "application", :media => nil
= javascript_include_tag "application"
= csrf_meta_tags
%body{'ng-app'=>'thumper','ng-controller'=>'MainController'}
- if signed_in?
.navbar.navbar-inverse.navbar-fixed-top{:style => 'padding-top:0px;height: 30px;'}
.container
%button.navbar-toggle{"data-target" => ".navbar-collapse", "data-toggle" => "collapse"}
%a.navbar-brand{:href => "/", :target => "_self"}
= image_tag "main_image.png", :style => 'width:65px;', :alt => 'company_name'
.navbar-collapse.collapse
%ul.nav.navbar-nav
%li
%a{:href => "/faq", :target => "_self"}
%i.fa.fa-lightbulb-o
FAQ
%li
This is my initial part of my application.html.haml file. I get the following error:
DEPRECATED: Please use restforce (https://github.com/ejholmes/restforce) instead.
=> Booting Thin
=> Rails 4.2.11 application starting in development on http://localhost:3000
=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server
Thin web server (v1.7.2 codename Bachmanity)
Maximum connections set to 1024
Listening on localhost:3000, CTRL+C to stop
Started GET "/testpage" for 127.0.0.1 at 2019-03-12 09:32:47 -0500
ActiveRecord::SchemaMigration Load (44.9ms) SELECT `schema_migrations`.* FROM `schema_migrations`
Processing by TestController#foo as HTML
HERE
Rendered test/foo.html within layouts/application (2.9ms)
Completed 500 Internal Server Error in 1964ms (ActiveRecord: 0.0ms)
ExecJS::RuntimeError - SyntaxError: [stdin]:959:20: unexpected =:
app/views/layouts/application.html.haml:7:in `_app_views_layouts_application_html_haml___861496224579637971_70314333220700'
app/lib/cors.rb:12:in `call'
app/lib/cors.rb:12:in `call'
Started POST "/__better_errors/1f18681361fed4ae/variables" for 127.0.0.1 at 2019-03-12 09:32:50 -0500
The web browser looks like this:

ActionView::Template::Error (undefined method `tr' for nil:NilClass

I am testing out the service-worker rails gem and am using VAPID private and public keys to send push notifications. I've succesfully been able to create push notifications locally, but when I deploy to heroku, the app raises the error stated above when trying to go to the push notification page. Here is the error:
75] Started GET "/push-simple/" for 69.253.120.203 at 2017-02-12 06:37:35 +0000
2017-02-12T06:37:35.339318+00:00 app[web.1]: [3d626b62-4c1b-41ca-aad3-fc653dc96b75] ActionView::Template::Error (undefined method `tr' for nil:NilClass
2017-02-12T06:37:35.333379+00:00 app[web.1]: [3d626b62-4c1b-41ca-aad3-fc653dc96b75] Rendering pages/push-simple.html.erb within layouts/application
2017-02-12T06:37:35.332337+00:00 app[web.1]: [3d626b62-4c1b-41ca-aad3-fc653dc96b75] Processing by PagesController#show as HTML
2017-02-12T06:37:35.336377+00:00 app[web.1]: [3d626b62-4c1b-41ca-aad3-fc653dc96b75] Rendered pages/push-simple.html.erb within layouts/application (2.8ms)
2017-02-12T06:37:35.336998+00:00 app[web.1]: [3d626b62-4c1b-41ca-aad3-fc653dc96b75] Completed 500 Internal Server Error in 4ms
2017-02-12T06:37:35.339281+00:00 app[web.1]: [3d626b62-4c1b-41ca-aad3-fc653dc96b75]
2017-02-12T06:37:35.339490+00:00 app[web.1]: [3d626b62-4c1b-41ca-aad3-fc653dc96b75] 13: <script type="text/javascript">
2017-02-12T06:37:35.339320+00:00 app[web.1]: Did you mean? try):
2017-02-12T06:37:35.339489+00:00 app[web.1]: [3d626b62-4c1b-41ca-aad3-fc653dc96b75] 11: </div>
2017-02-12T06:37:35.339489+00:00 app[web.1]: [3d626b62-4c1b-41ca-aad3-fc653dc96b75] 12:
2017-02-12T06:37:35.339561+00:00 app[web.1]: [3d626b62-4c1b-41ca-aad3-fc653dc96b75] app/views/pages/push-simple.html.erb:14:in `_app_views_pages_push_simple_html_erb__2838769268823495646_39526220'
2017-02-12T06:37:35.339491+00:00 app[web.1]: [3d626b62-4c1b-41ca-aad3-fc653dc96b75] 15: </script>
2017-02-12T06:37:35.339491+00:00 app[web.1]: [3d626b62-4c1b-41ca-aad3-fc653dc96b75] 14: var publicKey = new Uint8Array(<%= WebpushClient.public_key_bytes %>);
2017-02-12T06:37:35.339492+00:00 app[web.1]: [3d626b62-4c1b-41ca-aad3-fc653dc96b75] 16: <%= javascript_include_tag 'push-simple' %>
2017-02-12T06:37:35.339520+00:00 app[web.1]: [3d626b62-4c1b-41ca-aad3-fc653dc96b75]
2017-02-12T06:37:35.339560+00:00 app[web.1]: [3d626b62-4c1b-41ca-aad3-fc653dc96b75] app/clients/webpush_client.rb:7:in `public_key_bytes'
And here is my webpushclient where the VAPID keys are defined:
class WebpushClient
def self.public_key
ENV['VAPID_PUBLIC_KEY']
end
def self.public_key_bytes
Base64.urlsafe_decode64(public_key).bytes
end
def self.private_key
ENV['VAPID_PRIVATE_KEY']
end
# Send webpush message using subscription parameters
#
# #param message [String] text to encrypt
# #param subscription_params [Hash<Symbol, String>]
# #option subscription_params [String] :endpoint url to send encrypted message
# #option subscription_params [Hash<Symbol, String>] :keys auth keys to send with message for decryption
# #return true/false
def send_notification(message, endpoint: "", p256dh: "", auth: "")
raise ArgumentError, ":endpoint param is required" if endpoint.blank?
raise ArgumentError, "subscription :keys are missing" if p256dh.blank? || auth.blank?
Rails.logger.info("Sending WebPush notification...............")
Rails.logger.info("message: #{message}")
Rails.logger.info("endpoint: #{endpoint}")
Rails.logger.info("p256dh: #{p256dh}")
Rails.logger.info("auth: #{auth}")
Webpush.payload_send \
message: message,
endpoint: endpoint,
p256dh: p256dh,
auth: auth,
vapid: {
subject: "jon.corrin#gmail.com",
public_key: public_key,
private_key: private_key
}
end
def public_key
self.class.public_key
end
def private_key
self.class.private_key
end
end
and here is the script im using to call the public key:
<script type="text/javascript">
var publicKey = new Uint8Array(<%= WebpushClient.public_key_bytes %>);
</script>
<%= javascript_include_tag 'push-react' %>
Like I said before, it works locally. I think I may have forgotten to define a variable, I've looked at similar posts and have been debugging for quite some time, but have had no luck. Any suggestions? I also want to add, I'm quite new, so if it's an obvious error, I'll completely understand.
Your error is coming from this method:
def self.public_key_bytes
Base64.urlsafe_decode64(public_key).bytes
end
Looking up the source code for Base64#urlsafe_decode64, this is defined by:
def urlsafe_decode64(str)
strict_decode64(str.tr("-_", "+/"))
end
This is where your undefined method 'tr' for nil:NilClass must be coming from: the public_key. Which you have defined by:
def self.public_key
ENV['VAPID_PUBLIC_KEY']
end
...In other words, you have not set the environmental variable on your production server. That's why it works locally, but not on production.

NoMethodError users_url with devise (ajax)

I use devise 2.2.2 with rails 3.2.11
I use devise with ajax requests
I changed the following configuration in initializers/devise.rb
config.navigational_formats = [:json, :html]
config.http_authenticatable_on_xhr = false
when I submit an empty sign in request, I expect to get a json response with errors hash, but i get a 500 instead (see below for the trace) (it works fine with sign up request)
here are my routes (nothing special)
devise_for :users
the trace:
Started POST "/users/sign_in.json" for 127.0.0.1 at 2013-01-27 13:33:45 +0100
Processing by Devise::SessionsController#create as JSON
Parameters: {"user"=>{"email"=>"", "password"=>"[FILTERED]"}}
Completed 401 Unauthorized in 1ms
Processing by Devise::SessionsController#new as JSON
Parameters: {"user"=>{"email"=>"", "password"=>"[FILTERED]"}}
Completed 500 Internal Server Error in 40ms
NoMethodError (undefined method `users_url' for #<Devise::SessionsController:0x007fe88ddd9550>):
You are probably overriding after_sign_in_path_for and have a code path in there that returns nil.
This causes devise to fall back to its default behaviour and call users_url to get the path to redirect to.
Why do I think this? Because you are having the same error I had (and lost some hair over) and also this bug report contains the github usernames of many other people who have been humbled by this particular issue.

Rails 3 mailer not working and not logging any errors

I have tried all kinds of configurations but still I can't send an email in my development environment from rails.
I installed mailutils to try this from the command line and it worked, I received the email (in spam of course): echo test | mail -s Subject user#example.com
Here's my config:
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = true # still no logs about emails
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true # I can't believe I have to add this option. Does it even exist? I found it on google.
config.action_mailer.smtp_settings = {
:enable_starttls_auto => true,
:address => "smtp.gmail.com",
:port => 587,
:domain => "gmail.com",
:authentication => :login,
:user_name => "some_user#gmail.com",
:password => "abc123",
}
And here's the code in the mailer:
class UserMailer < ActionMailer::Base
default :from => "root#ubuntu"
def test_email
Rails.logger.debug 'test_email'
mail(:to => 'user#example.com', :subject => "testing rails")
end
end
The controller:
class PagesController < ApplicationController
def home
UserMailer.test_email
end
end
development.log:
[2012-03-01 18:26:45.859] DEBUG [bb44dee806d73eb60ab3ae16297f5c02] [127.0.0.1] [GET] [http://myapp:3000/] test_email
[2012-03-01 18:26:45.888] INFO [bb44dee806d73eb60ab3ae16297f5c02] [127.0.0.1] [GET] [http://myapp:3000/] Rendered user_mailer/test_email (1.6ms)
[2012-03-01 18:26:45.898] INFO [bb44dee806d73eb60ab3ae16297f5c02] [127.0.0.1] [GET] [http://myapp:3000/] Rendered pages/home.html.erb within layouts/application (1.1ms)
[2012-03-01 18:26:46.815] INFO [bb44dee806d73eb60ab3ae16297f5c02] [127.0.0.1] [GET] [http://myapp:3000/] Completed 200 OK in 455ms (Views: 112.4ms)
I also tried using the console:
root#ubuntu:/srv/www/myapp# rails c
Loading development environment (Rails 3.2.1)
irb(main):001:0> UserMailer.test_email
=> #<Mail::Message:32110400, Multipart: false, Headers: <To: user#example.com>, <Subject: testing rails>, <Mime-Version: 1.0>, <Content-Type: text/html>>
UserMailer.test_email
Just creates a Mail::Message object. To actually send an email you need to do
UserMailer.test_email.deliver
(or starting with rails 4.2 deliver_now / deliver_later)
Regarding logging errors:
Just figured out by tinkering that a bang method counterpart exists for deliver, which throws an exception. Can be pretty useful to check if you just misspelled your username or password, or you just have some misconfigured settings.
UserMailer.test_email.deliver!
An updated answer for Rails 4.2 would be:
UserMailer.test_email.deliver_now!
The exclamatory mark is to raise an exception if there are any errors.
If you suspect it's your settings, try taking out the :domain. It worked for me a while ago.( Net::SMTPAuthenticationError in rails 3.1.0.rc5 when connecting to gmail )
But I don't see a :body option in the mail function. Perhaps that's the issue. Try sending it from rails console and see what happens. http://api.rubyonrails.org/classes/ActionMailer/Base.html#method-i-mail

Resources