How to access to an object data in rails - ruby-on-rails

I have an object and want to access to some data but I have an error.
This is the object:
list = [{"id"=>0,"title"=>"Purple Rain"}, {"id"=>1,"title"=>"Life is a flower"},]
With binding.pry, i tried to access to the title of the first object by:
list.first.title
Can you tell me why it doesn't work? If i do "list.first", it will show the first object without any problem but when i want to access to only one data, i got this error:
NoMethodError: undefined method `title' for #<Hash:0x...
Thanks for your help

Hash doesn't have dot syntax. OpenStructs do. If you want to use dot syntax, then you can convert to openstruct if you want. But using what Sebastian suggested is fine.
list
# => [{"id"=>0, "title"=>"Purple Rain"}, {"id"=>1, "title"=>"Life is a flower"}]
list.first["title"]
# => "Purple Rain"
require 'ostruct'
# => true
obj = OpenStruct.new(list.first)
# => #<OpenStruct id=0, title="Purple Rain">
obj.title
# => "Purple Rain"

Related

Rails, hash failing when assigned to variable, but showing correct output when aborted

This should be an easy one. I have a method in my model that is doing this:
my_hash.max_by{ |k,v| v}[0]
I'm trying to get the key of the maximum value in the hash (by converting it to an array). If I do the following I get my intended results:
abort my_hash.max_by{ |k,v| v}[0] # Honda (for example)
When I do this, I get a undefined method `[]' for nil:NilClass.
brand = my_hash.max_by{ |k,v| v}[0]
What am I missing? Any thoughts or guesses are appreciated!
EDIT
my_hash
{"Honda"=> 4, "Toyota"=>2, "Ford"=>1}
The code was working when I have it directly in my view. Once I move it to the model and try and assign it to a variable, I get the above error.
Can you please share the key, value pair you are using in my_hash ?
I have tried this, and it is working for me:
irb(main):008:0> my_hash = {"CA"=>2, "MI"=>1, "NY"=>1}
=> {"CA"=>2, "MI"=>1, "NY"=>1}
irb(main):009:0> brand = my_hash.max_by{ |k,v| v}[0]
=> "CA"
The my_hash variable must be either an empty hash {} or array [] in your model. I think that it's the only way you'll get the error you observe.

Ruby: "undefined method `[]' for nil:NilClass" in a for loop

I am trying to populate my database using a for loop and JSON parsing. When I do not attempt a for loop and just do it for a single object, it works. Here is my code:
for i in 0..searchArray.size-1 #0..iTunesParsed['results'].size-1 // it is likely that searching for more than one item may not be benificial to us
# NOTE: Need to make sure to only search for artists, filter only songs
if !(ary.include? searchArray[i])
ary.push(searchArray[i])
# grabs artist name if not in database and adds it
# NOTE: this is occuring after the check for if elements are in the
# database, change it so this occurs first
if !(Artist.exists?(artist_name: ary[i]))
# replace all spaces with '+' so it may be passed to spotify
searchResult = searchArray[i]
if searchResult.match(/\s/)
searchResult.gsub!(/\s/,'+')
end
# grabbing the artist art from the Spotify api
# NOTE: have to fix 'special characters'
spotifyUrl = "https://api.spotify.com/v1/search?q=" + searchResult + "&type=artist"
spotifyUri = URI(spotifyUrl)
spotifyResponse = Net::HTTP.get(spotifyUri)
spotifyParsed = JSON.parse(spotifyResponse)
# When putting item into the database, replace '+' with a space
searchResult.gsub!('+',' ')
# create database entry
artist = Artist.create(:artist_name =>
searchResult, :artist_info=> nil,
:biography => nil, :recent_albums => nil, :rating => nil,
:related_artists => nil, :artist_art => spotifyParsed['artists']['items'][0]['images'][0]['url'])
end
end
The issue is mainly here:
artist_art => spotifyParsed['artists']['items'][0]['images'][0]['url'])
I have no idea what is happening. If anyone could guide me in the right direction, that would help a lot.
I believe there could be artists having no images. Use Rails’ try to handle these cases. Instead of:
:artist_art => spotifyParsed['artists']['items'][0]['images'][0]['url']
do:
:artist_art => spotifyParsed.try(:[],'artists')
.try(:[], 'items')
.try(:first)
.try(:[], 'images')
.try(:first)
.try(:[], 'url')
or use inline rescuer:
:artist_art => (spotifyParsed['artists']['items'][0]['images'][0]['url'] rescue nil)

Checking for nil result set before viewing

I've been reading Checking for nil in view in Ruby on Rails but I'm struggling to implement the marked solution.
I want to only load a graph in my View if a result set is not nil.
Controller:
#statistics = # ...my ActiveRecord query...
Helper:
def show_stats(statistics)
if statistics.pluck(:count)
image_tag(Gchart.line :size => '640x260',
:stacked => false,
:title => '',
:data => [statistics.pluck(:count)],
:legend => ['Stats'],
:bar_colors => ['3300CC', '3399FF'],
:axis_with_labels => ['y'])
end
end
View (HAML):
= show_stats(#statistics)
Currently when there are no statistics, I get an error. I want the View to not render the graph if there are no statistics. What am I doing wrong in the helper?
Error:
undefined method `-' for nil:NilClass
on the line where I call the helper.
if i understand correctly statistics.pluck(:count) will always return an array consisting of values of count attribute for each record found.
in ruby empty array evaluates to true, you might try to rewrite that if line like this:
if statistics.pluck(:count).any?
in fact it's good idea to cache that value and not fetch it from db again few lines below:
if (counts = statistics.pluck(:count)).any?
...
:data => [counts]
...
end
also i assume :data option wants array of values and not array of array of values so the final version would be:
if (counts = statistics.pluck(:count)).any?
...
:data => counts
...
end
P.S. if you still have an error - please share a full backtrace with us, knowing only "undefined method" doesn't tell much
Why not check for #statistics in your view like follows:
= show_stats(#statistics) if #statistics
Did you try this?
= show_stats(#statistics) unless #statistics.nil?

Equivalent of .try() for a hash to avoid "undefined method" errors on nil? [duplicate]

This question already has answers here:
How to avoid NoMethodError for nil elements when accessing nested hashes? [duplicate]
(4 answers)
Closed 7 years ago.
In Rails we can do the following in case a value doesn't exist to avoid an error:
#myvar = #comment.try(:body)
What is the equivalent when I'm digging deep into a hash and don't want to get an error?
#myvar = session[:comments][#comment.id]["temp_value"]
# [:comments] may or may not exist here
In the above case, session[:comments]try[#comment.id] doesn't work. What would?
You forgot to put a . before the try:
#myvar = session[:comments].try(:[], #comment.id)
since [] is the name of the method when you do [#comment.id].
The announcement of Ruby 2.3.0-preview1 includes an introduction of Safe navigation operator.
A safe navigation operator, which already exists in C#, Groovy, and
Swift, is introduced to ease nil handling as obj&.foo. Array#dig and
Hash#dig are also added.
This means as of 2.3 below code
account.try(:owner).try(:address)
can be rewritten to
account&.owner&.address
However, one should be careful that & is not a drop in replacement of #try. Take a look at this example:
> params = nil
nil
> params&.country
nil
> params = OpenStruct.new(country: "Australia")
#<OpenStruct country="Australia">
> params&.country
"Australia"
> params&.country&.name
NoMethodError: undefined method `name' for "Australia":String
from (pry):38:in `<main>'
> params.try(:country).try(:name)
nil
It is also including a similar sort of way: Array#dig and Hash#dig. So now this
city = params.fetch(:[], :country).try(:[], :state).try(:[], :city)
can be rewritten to
city = params.dig(:country, :state, :city)
Again, #dig is not replicating #try's behaviour. So be careful with returning values. If params[:country] returns, for example, an Integer, TypeError: Integer does not have #dig method will be raised.
The most beautiful solution is an old answer by Mladen Jablanović, as it lets you to dig in the hash deeper than you could with using direct .try() calls, if you want the code still look nice:
class Hash
def get_deep(*fields)
fields.inject(self) {|acc,e| acc[e] if acc}
end
end
You should be careful with various objects (especially params), because Strings and Arrays also respond to :[], but the returned value may not be what you want, and Array raises exception for Strings or Symbols used as indexes.
That is the reason why in the suggested form of this method (below) the (usually ugly) test for .is_a?(Hash) is used instead of (usually better) .respond_to?(:[]):
class Hash
def get_deep(*fields)
fields.inject(self) {|acc,e| acc[e] if acc.is_a?(Hash)}
end
end
a_hash = {:one => {:two => {:three => "asd"}, :arr => [1,2,3]}}
puts a_hash.get_deep(:one, :two ).inspect # => {:three=>"asd"}
puts a_hash.get_deep(:one, :two, :three ).inspect # => "asd"
puts a_hash.get_deep(:one, :two, :three, :four).inspect # => nil
puts a_hash.get_deep(:one, :arr ).inspect # => [1,2,3]
puts a_hash.get_deep(:one, :arr, :too_deep ).inspect # => nil
The last example would raise an exception: "Symbol as array index (TypeError)" if it was not guarded by this ugly "is_a?(Hash)".
The proper use of try with a hash is #sesion.try(:[], :comments).
#session.try(:[], :comments).try(:[], commend.id).try(:[], 'temp_value')
Update: As of Ruby 2.3 use #dig
Most objects that respond to [] expect an Integer argument, with Hash being an exception that will accept any object (such as strings or symbols).
The following is a slightly more robust version of Arsen7's answer that supports nested Array, Hash, as well as any other objects that expect an Integer passed to [].
It's not fool proof, as someone may have created an object that implements [] and does not accept an Integer argument. However, this solution works great in the common case e.g. pulling nested values from JSON (which has both Hash and Array):
class Hash
def get_deep(*fields)
fields.inject(self) { |acc, e| acc[e] if acc.is_a?(Hash) || (e.is_a?(Integer) && acc.respond_to?(:[])) }
end
end
It can be used the same as Arsen7's solution but also supports arrays e.g.
json = { 'users' => [ { 'name' => { 'first_name' => 'Frank'} }, { 'name' => { 'first_name' => 'Bob' } } ] }
json.get_deep 'users', 1, 'name', 'first_name' # Pulls out 'Bob'
say you want to find params[:user][:email] but it's not sure whether user is there in params or not. Then-
you can try:
params[:user].try(:[], :email)
It will return either nil(if user is not there or email is not there in user) or otherwise the value of email in user.
As of Ruby 2.3 this gets a little easier. Instead of having to nest try statements or define your own method you can now use Hash#dig (documentation).
h = { foo: {bar: {baz: 1}}}
h.dig(:foo, :bar, :baz) #=> 1
h.dig(:foo, :zot) #=> nil
Or in the example above:
session.dig(:comments, #comment.id, "temp_value")
This has the added benefit of being more like try than some of the examples above. If any of the arguments lead to the hash returning nil then it will respond nil.
#myvar = session.fetch(:comments, {}).fetch(#comment.id, {})["temp_value"]
From Ruby 2.0, you can do:
#myvar = session[:comments].to_h[#comment.id].to_h["temp_value"]
From Ruby 2.3, you can do:
#myvar = session.dig(:comments, #comment.id, "temp_value")
Another approach:
#myvar = session[:comments][#comment.id]["temp_value"] rescue nil
This might also be consider a bit dangerous because it can hide too much, personally I like it.
If you want more control, you may consider something like:
def handle # just an example name, use what speaks to you
raise $! unless $!.kind_of? NoMethodError # Do whatever checks or
# reporting you want
end
# then you may use
#myvar = session[:comments][#comment.id]["temp_value"] rescue handle
When you do this:
myhash[:one][:two][:three]
You're just chaining a bunch of calls to a "[]" method, an the error occurs if myhash[:one] returns nil, because nil doesn't have a [] method. So, one simple and rather hacky way is to add a [] method to Niclass, which returns nil: i would set this up in a rails app as follows:
Add the method:
#in lib/ruby_extensions.rb
class NilClass
def [](*args)
nil
end
end
Require the file:
#in config/initializers/app_environment.rb
require 'ruby_extensions'
Now you can call nested hashes without fear: i'm demonstrating in the console here:
>> hash = {:foo => "bar"}
=> {:foo=>"bar"}
>> hash[:foo]
=> "bar"
>> hash[:doo]
=> nil
>> hash[:doo][:too]
=> nil
Andrew's answer didn't work for me when I tried this again recently. Maybe something has changed?
#myvar = session[:comments].try('[]', #comment.id)
The '[]' is in quotes instead of a symbol :[]
Try to use
#myvar = session[:comments][#comment.id]["temp_value"] if session[:comments]

Cannot access data in active record using dot notation

I created a model in Ruby and am stuck on a n00b issue. In Rails Console:
s = Survey.where(:keyword => 'foo')
=> [#]
s.inittxtmsg
NoMethodError: undefined method inittxtmsg' for #<ActiveRecord::Relation:0x10350f8f8>
from /Library/Ruby/Gems/1.8/gems/activerecord-3.0.5/lib/active_record/relation.rb:371:inmethod_missing'
from (irb):3
Shouldn't I be able to see the values by typing s.Survey_id, s.inittxtmsg, s.keyword, s.store?
Thank you!
Survey.where(:keyword => 'foo')
returns an array of results, so you are really calling .inittxtmsg on an array, which obviously doesn't exist.
You could do something like:
Survey.where(:keyword => 'foo').first.inittxtmsg, in which it is calling it on the actual model object.
Or if you know that there is only one survey with the keyword = foo... you can use the find method to only return a single model object:
s = Survery.find_by_keyword("foo")
s.inittxtmsg

Resources