Upgraded app to Rails 5 using the index method. The issue is that it is not incrementing to the next ActiveRecord collection record. The below code below use to work in Rails 4.0. Tried with index_by.
def next_question
index = campaign.quiz_questions.index self
campaign.quiz_questions[index + 1]
end
Debugger
(byebug) campaign.quiz_questions.index
*** NoMethodError Exception: undefined method `index' for #<QuizQuestion::ActiveRecord_Associations_CollectionProxy:0x007f80012d71b0>
Did you mean? index_by
Using index_by
(byebug) index = campaign.quiz_questions.index_by
#<Enumerator: #<ActiveRecord::Associations::CollectionProxy [#<QuizQuestion id: 113, campaign_id: 492, message: "Where did Hullabalooza's freak show manager send H...", created_at: "2016-07-20 20:50:32", updated_at: "2016-07-20 20:50:32">]>:index_by>
Index + 1
(byebug) index + 1
*** NoMethodError Exception: undefined method `+' for #<Enumerator:0x007fc4db445960>
nil
changed it to find_index method. Now it's working
def next_question
index = campaign.quiz_questions.find_index self
campaign.quiz_questions[index + 1]
end
Related
I'm creating a new Rails app with Rails 6 and I want to do something like this:
#items = Item.all.unshift Item.new(id: 0, name: '-- Kein Item --')
But I get the error "undefined method `unshift' for #<ActiveRecord::Relation [#<Item id: 1, name: "Item 1", created_at: "2021-03-13 11:09:34.284978000 +0000", updated_at: "2021-03-13 11:09:34.284978000 +0000">]>"
In another Rails app I can do it, but that app is running under Rails 4.
I want to add this "empty" record so that model project hast not everytime an item and because I have somewhere Project.item.name it won't give an nil error.
Any suggestions?
In my application_controller.rb, i have a line of code as follows:
def index
CaseStatus.order(:application_source).pluck(:application_source).uniq!
end
In my rspec code, i have a line of code that visits the index path of application_controller as follows
visit applications_path
When i run the code directly, it works perfectly but when it visits application_controller.rb via rspec, i get an error which says
NoMethodError:
undefined method `compact' for nil:NilClass
Not sure while i get this error via rspec and capybara but if i run the code as
def index
CaseStatus.order(:application_source).pluck(:application_source)
end
It executes perfectly with no errors. Kinda confused what the uniq! breaks in the code that suddenly the result becomes nil.
i get this error
Failure/Error: #application_channels = CaseStatus.order(:application_source).pluck(:application_source).uniq!.compact if CaseStatus.order(:application_source).present?
NoMethodError:
undefined method `compact' for nil:NilClass
# ./app/controllers/loan_applications_controller.rb:53:in `index'
I do not think uniq! is the method you would like to use in this case, see:
Returns nil if no changes are made (that is, no duplicates are found).
https://ruby-doc.org/core-2.2.0/Array.html#method-i-uniq-21
So it works like this:
2.3.1 :008 > a = [1,2,3,3,nil].uniq!
=> [1, 2, 3, nil]
2.3.1 :009 > a = [1,2,3,nil].uniq!
=> nil
2.3.1 :010 >
on the other hand uniq works like:
2.3.1 :010 > a = [1,2,3,3,nil].uniq
=> [1, 2, 3, nil]
2.3.1 :011 > a = [1,2,3,nil].uniq
=> [1, 2, 3, nil]
and on the output of uniq it is safe to run compact to remove nil values.
I am attempting to build a simple web app that takes data passed in to a text field and delivers it to an API. I have created a model with some methods to do some basic calls to the API. I have set up a form with a text field and a submit button to pass along the data to a controller. When I submit I am getting an error that the method I am calling is not defined. Yet if I go in the console and try the same thing it works as expected. Any suggestions on what I am missing?
Model:
def update(serial, deploy_value)
HTTParty.post("#{BASE_URL}devices/update/serial/#{serial}?#{API_KEY}",
:body => {"customFieldValues": [{"name": "Deploy","value": "#{deploy_value}"}] }.to_json,
:headers => { 'Content-Type' => 'application/json'}
)
end
Controller
class GroundControlController < ApplicationController
require 'GroundControl'
def update
serial = params[:serial]
GroundControl.new.update(serial, "TEST")
redirect_to(:back)
end
end
The error I am getting:
NoMethodError in GroundControlController#update
undefined method `update' for GroundControl:0x007fa062aa1298
From the console I can do the following:
2.3.0 :002 > require 'GroundControl'
=> true
2.3.0 :003 > test = GroundControl.new
=> #<GroundControl:0x007fa2676a8838>
2.3.0 :004 > GroundControl.new.update("ABC123", "TEST")
=> #<HTTParty::Response:0x7fa2671fb218 parsed_response={"id"=>43270, "serial"=>"ABC123", "udid"=>nil, "name"=>nil, "model"=>nil, "os"=>nil, "connected"=>false, "customFieldValues"=>[{"name"=>"Deploy", "value"=>"TEST"}]}, #response=#<Net::HTTPOK 200 OK readbody=true>, #headers={"server"=>["nginx/1.6.3"], "date"=>["Tue, 12 Apr 2016 15:09:27 GMT"], "content-type"=>["application/json; charset=utf-8"], "content-length"=>["150"], "connection"=>["close"], "access-control-allow-origin"=>["*"]}>
2.3.0 :005 >
More info on the error I am getting:
NoMethodError in GroundControlController#update
undefined method `update' for #
Extracted source (around line #10):
8 def update
9 serial = params[:serial]
10 GroundControl.new.update(serial, "TEST")
11 redirect_to(:back)
12
13 end
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've a model Dish and PriceDeal as follows
class Dish < ActiveRecord::Base
has_one :price_deal
end
class Dish < ActiveRecord::Base
belongs_to :dish
end
In rails console, I want to retrive the discountPercent value like this.
1.9.2p290 :130 > pd=PriceDeal.find(17)
=> #<PriceDeal id: 17, name: "deal1", description: "my deal1", discountPercent: 20.0, discountCash: nil, dish_id: 2, created_at: "2012-03-22 07:42:08", updated_at: "2012-04-16 11:16:49">
1.9.2p290 :131 > pd.discountPercent
=> 20.0
I got the expected result.
But when I try to get the value like this,
1.9.2p290 :132 > pd1 = PriceDeal.where(:dish_id => 2)
=> [#<PriceDeal id: 17, name: "deal1", description: "my deal1", discountPercent: 20.0, discountCash: nil, dish_id: 2, created_at: "2012-03-22 07:42:08", updated_at: "2012-04-16 11:16:49">]
1.9.2p290 :133 > pd1.discountPercent
NoMethodError: undefined method `discountPercent' for #<ActiveRecord::Relation:0xa134958>
from /home/ragunathjawahar/.rvm/gems/ruby-1.9.2-p290#rails3tutorial/gems/activerecord-3.0.11/lib/active_record/relation.rb:374:in `method_missing'
from (irb):133
from /home/ragunathjawahar/.rvm/gems/ruby-1.9.2-p290#rails3tutorial/gems/railties-3.0.11/lib/rails/commands/console.rb:44:in `start'
from /home/ragunathjawahar/.rvm/gems/ruby-1.9.2-p290#rails3tutorial/gems/railties-3.0.11/lib/rails/commands/console.rb:8:in `start'
from /home/ragunathjawahar/.rvm/gems/ruby-1.9.2-p290#rails3tutorial/gems/railties-3.0.11/lib/rails/commands.rb:23:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
I got error,
How to get the value of discountPercent from pd1.
Thanks.
The reason why this is happening is because when you use where, you get back not a single object of type PriceDeal, but you get an object of type ActiveRecord::Relation, which for all intents and purposes is an array.
Notice how you got:
[#<PriceDeal id: 17, name: "deal1", ... >]
Instead of just:
#<PriceDeal id: 17, name: "deal1", ... >
The braces ([]) mean that it's an array. So you'll have to do this:
pd1.first.discountPercent
The reason why the where method returns an array is because you can have multiple items returned. Imagine doing:
PriceDeal.where("discountPercent >= 0")
You'd probably get a lot of records from that.
pd=PriceDeal.find(17)
It will return only one particular column.so you will not get no method error.
when you are using Modelname.where("conditions").The results will be array.so you will get no method error.Because your method is not present to array.