I am using omniauth on my rails project to authenticate with facebook.
I am also trying to get the user's current city from omniauth, and that works great when the user has their current city in facebook.
extra:
user_hash:
name: Jeff Turner
location:
name: Oakland, California
but when the user doesn't have anything, I cant set that value
current_city = user_data['location']['name']
error:
You have a nil object when you didn't expect it!
You might have expected an instance of ActiveRecord::Base.
The error occurred while evaluating nil.[]
I can see that no value with those attributes even come back from omniauth
if I try to test for the nil condition
if user_data['location']['name'].blank? == false
current_city = user_data['location']['name']
end
I seem to get the same error on that first line (user_data['location']['name'].blank?)
still cant evaluate nil.
I am pretty new to rails, so I hope I just missed something obvious.
Update
this is what I ended up changing it to and it worked fine. answer below looks like it would work as well
if user_data['location'].nil? == false
if user_data['location']['name'].nil? == false
current_city = user_data['location']['name']
end
end
You can try doing something like this:
current_city = auth.fetch('location', []).fetch('name', nil)
Using fetch.
Related
I've been running a piece of code for a while with success but it has just started throwing an error - we've altered the way data is going into the database but believe it's more likely a programming issue or I've altered it by mistake, but can't see where.
The issue appears to be caused form a scope, we're running Rails 4.2.2
The complete error is
undefined method `call' for
ActiveRecord::QueryMethods::WhereChain:0x007feb8f5c49f0> Did you mean? caller
app/controllers/orders_controller.rb:158:in `weekly_sales_report'
in my orders_controller line 158
#sales_this_week_bysales = Order.select("COUNT(order_id) AS nosales, AVG(net_amount) AS avgsale,SUM(sale_cost) AS sale_cost, SUM(net_amount) AS weeklysalestotal, owner_id AS salesman").sales.where.(date_of_sale: (#startdate .. #enddate)).with_salesman.group(:owner_id)
in my orders.rb model I have the following used scopes
scope :with_salesman, -> { joins(:pipe_records).where(pipe_records: {pipe_part_id: 1}).where.not(pipe_records: {owner_id: nil}) }
scope :sales, -> {where ("orders.order_ref <>'' and date_of_sale IS NOT NULL ")}
I re-wrote the scope to the below but still got the same error
scope :with_salesman, -> { joins(" INNER JOIN pipe_records ON pipe_records.order_id = orders.id WHERE pipe_records.pipe_part_id =1 AND pipe_records.owner_id <>'' ") }
I also removed the WHERE startdate criteria from the sales.where on 158 which returned a different error, but it appears the scope isn't passing correctly anymore or returning an error due to bad records??
I'm now unsure what is happening, I went back to my remotes and took a copy of the code from a couple of days ago and this also threw the same error, but it was working correctly. We've put a lot of new records in recently through a new form which bypasses and alters created at dates which may be to blame. I would appreciate any suggestions or fresh eyes.
Just remove the period between where and the parenthesis.
where.(date_of_sale: (#startdate..#enddate))
In ruby
receiver.()
is short hand for receiver.call() thus the error you are receiving
You probably want to remove that period after where:
where.(date_of_sale: (#startdate .. #enddate))
Using the code:
function createNewBody(name,mass)
if not world.body[name]==nil then
print("This body has already been created. Maybe you meant to update it's values?\n")
else
world.body[name]={mass=m,x=0,y=0,xAccel=0,yAccel=0,xR=0,yR=0,properties={gaseous=false,texture=""}}
world.bodies=world.bodies+1
end
end
This code shows no errors, but when I bind createNewBody(moon,1.622) to a key and then use it, it lets me spam the key without showing the error message.
And, yes, I have defined world.bodies and world.body
not world.body[name]==nil is parsed as (not world.body[name])==nil. Since the result of not is a boolean, it is never nil.
Try not(world.body[name]==nil) or world.body[name]~=nil.
We recently upgraded to Rails 4.2 from Rails 4.1 and are seeing problems with using Arel + Activerecord because we're getting this type of error:
ActiveRecord::StatementInvalid: PG::ProtocolViolation: ERROR: bind message supplies 0 parameters, but prepared statement "" requires 8
Here's the code that is breaking:
customers = Customer.arel_table
ne_subquery = ImportLog.where(
importable_type: Customer.to_s,
importable_id: customers['id'],
remote_type: remote_type.to_s.singularize,
destination: 'hello'
).exists.not
first = Customer.where(ne_subquery).where(company_id: #company.id)
second = Customer.joins(:import_logs).merge(
ImportLog.where(
importable_type: Customer.to_s,
importable_id: customers['id'],
remote_type: remote_type.to_s.singularize,
status: 'pending',
destination: 'hello',
remote_id: nil
)
).where(company_id: #company.id)
Customer.from(
customers.create_table_alias(
first.union(second),
Customer.table_name
)
)
We figured out how to solve the first part of the query (running into the same rails bug of not having bindings) by moving the exists.not to be within Customer.where like so:
ne_subquery = ImportLog.where(
importable_type: Customer.to_s,
importable_id: customers['id'],
destination: 'hello'
)
first = Customer.where("NOT (EXISTS (#{ne_subquery.to_sql}))").where(company_id: #company.id)
This seemed to work but we ran into the same issue with this line of code:
first.union(second)
whenever we run this part of the query, the bindings get lost. first and second are both active record objects but as soon as we "union" them, they lose the bindings are become arel objects.
We tried cycling through the query and manually replacing the bindings but couldn't seem to get it working properly. What should we do instead?
EDIT:
We also tried extracting the bind values from first and second, and then manually replacing them in the arel object like so:
union.grep(Arel::Nodes::BindParam).each_with_index do |bp, i|
bv = bind_values[i]
bp.replace(Customer.connection.substitute_at(bv, i))
end
However, it fails because:
NoMethodError: undefined method `replace' for #<Arel::Nodes::BindParam:0x007f8aba6cc248>
This was a solution suggested in the rails github repo.
I know this question is a bit old, but the error sounded familiar. I had some notes and our solution in a repository, so I thought I'd share.
The error we were receiving was:
PG::ProtocolViolation: ERROR: bind message supplies 0 parameters, but
prepared statement "" requires 1
So as you can see, our situation is a bit different. We didn't have 8 bind values. However, our single bind value was still being clobbered. I changed the naming of things to keep it general.
first_level = Blog.all_comments
second_level = Comment.where(comment_id: first_level.select(:id))
third_level = Comment.where(comment_id: second_level.select(:id))
Blog.all_comments is where we have the single bind value. That's the piece we're losing.
union = first_level.union second_level
union2 = Comment.from(
Comment.arel_table.create_table_alias union, :comments
).union third_level
relation = Comment.from(Comment.arel_table.create_table_alias union2, :comments)
We created a union much like you except that we needed to union three different queries.
To get the lost bind values at this point, we did a simple assignment. In the end, this is a little simpler of a case than yours. However, it may be helpful.
relation.bind_values = first_level.bind_values
relation
By the way, here's the GitHub issue we found while working on this. It doesn't appear to have any updates since this question was posted though.
I'm using the gem called "rails3-jquery-autocomplete" ( https://github.com/crowdint/rails3-jquery-autocomplete )
It's working fine:) But there's one thing that I want to disable.
When I type something into an input field, and there's no matching record, it always show the message that's saying "no existing match"
I want to disable this message. Is it possible?
I wish I could see inside of its source code to customize but I cannot :(
Anyone can help me about this?
This might be piece of cake for someone but not for me.
For your information, I've done this command below
$ bundle exec rake assets:precompile RAILS_ENV=production
and after this it created some js files into public/assets folder
Seems there is no way to pass option into the control, but I assume this might be a trick to solve your problem.
Instead of returning empty array(from backend) when no search results, try to return a array with one result has empty id and label might solve your problem, so in your rails controller, there will be something like this:
def autocomplete_action
result = do_the_search
if result.count == 0
result = [{ id: "", label: "" }] # !! do the trick here
end
respond_with result # assume you have "respond_to :json" in your controller
end
Here is why I am doing this:
The reason why I think this might work is because if no result return, the autocomplete control will build a fake record with id equals to empty represent no result.
if(arguments[0].length == 0) {
arguments[0] = []
arguments[0][0] = { id: "", label: "no existing match" } // hacked here
}
But I do think this definitely not the right way to solve this problem, but for now it's workaround to solve your problem quickly.
Hope it helps, thanks.
I'm about to lose my mind due to a simple Rails where query. I simply cannot understand why it does work like 10 lines ago and does not after it. I could not figure out what might be causing the problem
#userID = Token.where(:tokenCode => #tokenReceived)
##init.tokenCode=#tokenReceived+"1" #randomize algorithm required!
#init.tokenCode=#codeGenerated=generate_activation_code()
if #userID.nil?
#newToken=Token.new
#newToken.tokenCode=#codeGenerated
else
#tokenToAdd = "12"
#newToken=Token.where(:userID => "1")
#if #newToken.nil?
#newToken.tokenCode="12"
#end
end
##newToken.save
#init.save
When I make a successful JSON request to 'http://localhost:3000/inits.json' it gives me a page with tons of erros but I think the main error among those are:
<h1>
NoMethodError
in InitsController#create
</h1>
<pre>undefined method `tokenCode=' for #<ActiveRecord::Relation:0x007fc43cb40b88></pre>
What could be the reason? Am I writing the where clause all wrong?
Edit: When I activate the if clause it works. I simply believe the #newToken object is null, however it is almost impossible for me to detect why. There is a data in my Token table with userID 1.
When you do:
#newToken=Token.where(:userID => "1")
You get an ActiveRecord::Relation, but you expect an object. So simply replace it with:
#newToken=Token.where(:userID => "1").first