Im getting a weird string error when trying to assign attributes on a Rails model:
# POST /apartments
# POST /apartments.xml
def create
#apartment = Apartment.new(params[:apartment])
Params
{"utf8"=>"✓",
"authenticity_token"=>"Kxxxxx=",
"apartment"=>{"street"=>"123 Main St",
"unit"=>"",
"hide_address"=>"0",
"city"=>"White Plains",
"state"=>"New York",
"zipcode"=>"10840",
"country"=>"United States",
"price"=>"4000",
"security_deposit"=>"",
"application_fee"=>"",
"bedrooms"=>"4",
"bathrooms"=>"3",
"size"=>"",
"available_date"=>"",
"unit_amenities"=>["air conditioning"],
"description"=>"",
"rooms"=>"1"},
"commit"=>"Publish Your Listing"}
Error
NoMethodError in ApartmentsController#create
undefined method `each' for "1":String
Thoughts?
Related
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.
I am trying to create an ActionCable chatroom following the actioncable guide on GoRails.com.
As I am trying to connect to ActionCable I get following error:
NoMethodError - undefined method `safe_constantize' for nil:NilClass
[ActionCable] [User 1] Could not execute command from
{"command"=>"subscribe", "identifier"=>"
{\"ChatroomsChannel\":\"ChatroomsChannel\",\"room_id\":1}"})
[NoMethodError - undefined method `safe_constantize' for
nil:NilClass]: /Users/Mathias/.rvm/gems/ruby-
2.2.3#chatroomv1/gems/actioncable-
5.0.0.rc2/lib/action_cable/connection/subscriptions.rb:29:in `add' |
/Users/Mathias/.rvm/gems/ruby-2.2.3#chatroomv1/gems/actioncable-
5.0.0.rc2/lib/action_cable/connection/subscriptions.rb:15:in
`execute_command' | /Users/Mathias/.rvm/gems/ruby-
2.2.3#chatroomv1/gems/actioncable-
5.0.0.rc2/lib/action_cable/connection/base.rb:88:in
`dispatch_websocket_message' | /Users/Mathias/.rvm/gems/ruby-
2.2.3#chatroomv1/gems/actioncable-
5.0.0.rc2/lib/action_cable/server/worker.rb:54:in `block in invoke' |
/Users/Mathias/.rvm/gems/ruby-2.2.3#chatroomv1/gems/actioncable-
5.0.0.rc2/lib/action_cable/server/worker.rb:39:in `block in work'
My app/channels/chatrooms_channel.rb looks like this:
def subscribed
#chatroom = Chatroom.find(params[:room_id])
#puts params[:room_id]
#current_user.join_room(#chatroom)
stream_from "chatrooms:#{#chatroom.id}"
# stream_from "some_channel"
end
Maybe it is worth mentioning that I upgraded to rails 5.0.0.rc2 from rails 4.
Thank you,
in assets/javascripts/channels/chatroom.coffee
If you need to assign params, channel name must be in params hash too:
App['chatroom' + roomId] = App.cable.subscriptions.create {
channel: 'ChatroomChannel',
room_id: roomId
}, {
received: ->
...
}
And only if you don't need params, you can write channel name without hash:
App.chatroom = App.cable.subscriptions.create 'ChatroomChannel',
received: ->
...
I am using simple_form in rails, and I have this as checkbox:
<%= f.input :delivery_days, as: :check_boxes,
collection: [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Satusday',
'All'],
wrapper: :vertical_radio_and_checkboxes
%>
I am not able to get the values of selected checkboxes in my controller.
I am using the following code to get it:
def user_basic_params
logger.info "from user_basic_params"
params.require(:profile).permit(:delivery_days[])
end
I have other form fields but they are getting handled correctly and I am able to get their values.
Console output is :
Started POST "/profiles" for 127.0.0.1 at 2015-06-02 02:07:56 +0530
Processing by ProfilesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"w3RvztJtKq56qimpZPj3KD9S5pr1vbw2K6b7eToaEV5rEuBsx1jqJ8gITg+uHq8TgBoeYZPsczQLghWg2fhpCg==", "profile"=>{"milk_animal"=>"Any", "milk_type"=>"Any", "brand"=>"Amul", "time_of_delivery(1i)"=>"2015", "time_of_delivery(2i)"=>"6", "time_of_delivery(3i)"=>"1", "time_of_delivery(4i)"=>"20", "time_of_delivery(5i)"=>"37", "start_date(1i)"=>"2015", "start_date(2i)"=>"6", "start_date(3i)"=>"1", "delivery_days"=>["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Satusday", "All", ""], "name"=>"Sony", "address"=>"asdfghjk", "pincode"=>"zxcvbnm,", "contact_no"=>"2345678"}, "commit"=>"Create Profile"}
from create
from user_basic_params
Completed 500 Internal Server Error in 1ms (ActiveRecord: 0.0ms)
ArgumentError (wrong number of arguments (0 for 1..2)):
app/controllers/profiles_controller.rb:53:in `[]'
app/controllers/profiles_controller.rb:53:in `user_basic_params'
app/controllers/profiles_controller.rb:18:in `create'
The problem is in the permit(:delivery_days[]) part of your code. Rails expects the brackets to contain 1 or 2 parameters, but you are passing none, thus raising an error.
I am not sure why the brackets are there, try removing them and I believe your code should work.
Replace this
params.require(:profile).permit(:delivery_days[])
with
params.require(:profile).permit(:delivery_days)
I have the following code (with a few debug lines added):
Ruby:
re_dict = {}
re_dict['state'] = 'pending' #set initial status to pending
puts re_dict, re_dict.class.to_s
puts re_dict['state'], re_dict['state'].class.to_s
puts re_dict['state'].casecmp('pending')
while re_dict['state'].casecmp('pending') == 0 do
stuff
end
Output
state: pending
state class: String
class compared to 'pending': 0
Completed 500 Internal Server Error in 66ms
NoMethodError (undefined method `casecmp' for nil:NilClass):
What is causing this? How am I losing the value of my hash?
This will happen only when you remove 'state' key from re_dict hash inside your while loop:
while re_dict['state'].casecmp('pending') == 0 do
puts re_dict
re_dict = {}
end
#=> {"state"=>"pending"}
#=> NoMethodError: undefined method `casecmp' for nil:NilClass
Since, key 'state' is not available anymore, calling re_dict['state'] will give nil, that's why you're getting undefined method casecmp' for nil:NilClass
i am using rails 2.3.4 and i am facing "no method error"
there is possibility to not find method but my question is - is there possibility to error occurred because of empty table? or error in another controller or helper?
error trace:
Processing QuoteRequestsController#create (for 127.0.0.1 at 2012-10-17 16:07:34) [POST]
Parameters: {"controller"=>"quote_requests", "quote_request"=>{"packing_required"=>"", "move_steps_number"=>"", "phone_day"=>"", "pickup_region_id"=>"", "email"=>"", "move_to_street"=>"", "move_from_suburb"=>"", "title"=>"", "quick_estimate"=>"true", "room_counts"=>{"9"=>"0", "8"=>"0", "5"=>"0", "2"=>"0", "3"=>"0", "6"=>"0", "7"=>"0", "1"=>"0", "4"=>"", "11"=>"0"}, "arrive_parking_notes"=>"", "first_name"=>"", "arrive_date_flexible"=>"false", "insurance_value"=>"", "arrive_steps_number"=>"", "move_parking_notes"=>"", "last_name"=>"", "move_region_id"=>"", "move_date_flexible"=>"false", "move_type_id"=>"26", "move_to_city"=>"", "arrive_date"=>"", "move_from_street"=>"", "move_date"=>"", "move_to_suburb"=>"", "move_from_city"=>"", "phone_mobile"=>""}, "authenticity_token"=>"U42qF1c0FJXvnC1SCNNYWzxKN3Pem7dC6L01LbTQD7E=", "commit"=>"Submit", "action"=>"create"}
NoMethodError (undefined method service_options' for nil:NilClass):
vendor/extensions/smartmove/app/controllers/quote_requests_controller.rb:136:inload_regions'
vendor/radiant/vendor/plugins/haml/rails/./lib/sass/plugin/rails.rb:19:in `process'
/home/bacancy/.rvm/rubies/ruby-1.8.7-p370/lib/ruby/1.8/webrick/httpserver.rb:104:in `service'
/home/bacancy/.rvm/rubies/ruby-1.8.7-p370/lib/ruby/1.8/webrick/httpserver.rb:65:in `run'
/home/bacancy/.rvm/rubies/ruby-1.8.7-p370/lib/ruby/1.8/webrick/server.rb:173:in `start_thread'
/home/bacancy/.rvm/rubies/ruby-1.8.7-p370/lib/ruby/1.8/webrick/server.rb:162:in `start'
/home/bacancy/.rvm/rubies/ruby-1.8.7-p370/lib/ruby/1.8/webrick/server.rb:162:in `start_thread'
/home/bacancy/.rvm/rubies/ruby-1.8.7-p370/lib/ruby/1.8/webrick/server.rb:95:in `start'
/home/bacancy/.rvm/rubies/ruby-1.8.7-p370/lib/ruby/1.8/webrick/server.rb:92:in `each'
/home/bacancy/.rvm/rubies/ruby-1.8.7-p370/lib/ruby/1.8/webrick/server.rb:92:in `start'
/home/bacancy/.rvm/rubies/ruby-1.8.7-p370/lib/ruby/1.8/webrick/server.rb:23:in `start'
/home/bacancy/.rvm/rubies/ruby-1.8.7-p370/lib/ruby/1.8/webrick/server.rb:82:in `start'
in "vendor/extensions/smartmove/app/controllers/quote_requests_controller.rb" line no:136 is
#regions = ServiceDescription.find_by_name('region').service_options
in my database table is there service_descriptions and service_options. is there related to mysql or controller?
please guide me i am very much confuse. this is existing application i have to configure in local as well as on server
Thank you in advance
Thanking You
Nirav
You are getting error because ServiceDescription.find_by_name('region') returns nil (This simply means you have no data in your service_descriptionstable with name 'region') and then you are calling service_options on it (i.e. nil)
Best way to avoid such case is to check if value is nil or not before applying any method it.
#regions = ServiceDescription.find_by_name('region')
#service_options = #regions ? #regions.service_options : nil