I'm trying to understand how I'm getting two different outputs from rails
If I have this:
<%= if value.user.present?
link_to value.user.email, value.user
end %>
I gives me what I wanted. It out puts the email of the user with its link associated with it.
But when I take the if statement out,
<%= link_to value.user.email, value.user %>
I get this error.
undefined method `email' for nil:NilClass
I don't get it? Aren't I just doing the same thing with the first statement? It outputs the link_to.
Why am I get two different outputs with what I thought was the same statement?
That's happening because you called a method on nil (value.user is nil)
An easy way to shorten it up...
<%= link_to(value.user.email, value.user) if value.user %>
A note, if value.user could be nil (not false), but is still considered 'falsey' in ruby.
in your if condition it checks whether your user is present and if present it will give the proper output... but somehow if your user is not present it will check like for nil and generates that error, to avoid that you have to write the condition or rescue nil on that line...
This error would pop up if any of your value.user items do not have an email associated.
I've encountered this when migrating and not all rows have the item assigned.
Related
I'm getting this following error:
undefined method `assessment' for nil:NilClass
My code below has the conditional unless to exclude if the method is nil, but is not working. I have also tried the if conditional as well, but not no avail.
I think I need to default to a number if assessment is nil, but unsure on how to do that.
The date is formatted in milliseconds: 1482985235000
<% #sales.methods.each do |data| %>
<%= Time.at(data.assessment.assessment_date/1000).strftime("%d/%m/%Y") unless data.assessment.assessment_date.nil? %>
<% end %>
Try using safe navigation operator or have a chain of try.
data.try(:assessment).try(:assessment_date).nil?.
Or by using safe navigation operator.
data&.assessment&.assessment_date.nil?.
This error is generated when any method is called on nil. If data is nil then assessment will generate error if assessment is nil then assessment_date will. Either way you need to make sure both are present.
We generally don't use inline rescue and handle this type of scenarios by checking both objects. You can go with any of option or you can also check data.assessment.present? && data.assessment.assessment_date.present?
The error says that you are calling the method assessment on a nil... this means that the thing that is nil is data. Your conditional is checking whether data.assessment.assessment_date is nil... but it won't even get to the check for whether assessment_date is nil because it's already failing at data.assessment
I have found a solution to the problem. Not sure if it's the best method, but it works. I added rescue 0 to the end of the call.
<% #sales.methods.each do |data| %>
<%= Time.at(data.assessment.assessment_date/1000).strftime("%d/%m/%Y") rescue 0 %>
<% end %>
Can someone explain the logic behind this code?(This is the correct code btw)
<% if #request.query['first_name'] && !#request.query['first_name'].empty? %>
Welcome! <%= #request.query['first_name'] %>
<% else %>
Hi! What is your name?
<% end %>
My intuition is to write the following instead:
<% if #request.query.inspect['first_name'].empty? %>
Hi! What is your name?
<% else %>
Welcome! <%= #request.query.inspect['first_name'] %>
<% end %>
I am trying to have a user form where people can input their names, when there is no input yet the text above the form says "Hi! What is your name?" when there is an input it has a message saying "Welcome! *User_name*"
The first block of code is not intuitive to me, the second one would make more sense.. ANy advice on how to understand the code?
Your intuition is correct, though you need an alternative to empty?. Rails adds a few different methods you can use:
blank? returns true if the receiver is nil, an empty array, string, or hash, or a string with only whitespace.
present? returns true if blank? is false. So your condition could be:
<% if #request.query['first_name'].present? %>
Welcome...
(I find it's always more intuitive to start with the positive condition - it would work just as well to check blank?).
Edit: It's pretty likely you can skip the query method entirely if all you expect there is either a string or nil. Just use:
<% if #request.query['first_name'] %>
You need to check if it's nil before you can check if its empty, because you are checking a Hash#empty?
irb(main):001:0> nil.empty?
NoMethodError: undefined method `empty?' for nil:NilClass
from (irb):1
irb(main):002:0> {}.empty?
=> true
The code checks for hash key existence, then check if the value of the hash is present. This action can be done in one check using:
#request.query.try(:[], 'first_name').empty?
You can avoid the first condition inside the if statement by transforimng nil into an empty string. I don't know if that is what you meant to do but you almost had.
First, you shouldn't call inspect in the hash because it will transform the entire thing into a 'complex' string. What you want to do turn only the value inside the first_name option, because in that case if the name exists it will still be the same, and if it doesn't, it will be turned into "nil".
Secondly, the method inspect isn't the best choice here, because the returned string will never be empty, given that nil.inspect => "nil". What you should use is the method to_s, wich will behave like this when applied to nil: nil.to_s => "".
Finally, you could update your code to:
<% if #request.query['first_name'].to_s.empty? %>
Hi! What is your name?
<% else %>
Welcome! <%= #request.query['first_name'] %>
<% end %>
For some reason, I keep getting an "undefined method 'each'" error every time I try to do the .each do when I have one result in the below.
If I use .inspect, I can see that there's a match. Does .each work if there's not more than 1 result? If not, what should I use instead?
<% friends = graph.get_object("/me/friends").map{ |hash| hash["id"] } %>
<% User.select([:id]).where(fbookid: friends).each do |common| %>
<% end %>
If I just run .inspect on the User.select line (no each), then I get
[#<User id: 1>]
Any help would be appreciated!
Thank you!
UPDATE
Adding additional parameters seemed to allow me to use each...I have no clue why. It's the same exact result (only 1).
User.select([:id, :email, :first_name]).where(fbookid: friends).each do |friend|
You get simple object not array so that it's not working. .each method working when if you get array you get simple object so that you can use direct means that
for example
# if name attributes
User.select([:id]).where(fbookid: friends).name
You can use each on User.select([:id]).where(fbookid: friends), even if there is only 1 element. It will not raise an exception even if there are no elements.
The error is happening somewhere else. Perhaps you are getting an error on something inside the each loop.
Can you post more code?
The code below displays peferctly what i want to accomplish (show store name and item name).But when i subtitute #onedeal=#deal.find_with_ids(62) with #onedeal=#deal.find(params[:id]) i get an error Couldn't find Deal without an ID.What method should i use to fetch deal ID dynamically?The relationship between the Deal and store model is has many :through.
controller
#deal=#city.deals
#onedeal=#deal.find_with_ids(62)
#store=#onedeal.stores.first(params[:store_id])
view
<% #deal.each do |deal| %>
<%=deal.item_name %>
<%end%>
<%=#store.store_name %>
That error means that params[:id] is empty. Check your params hash to see what it contains, and verify that your action is getting the input it expects.
You are absolutely using the .find method as intended, so I don't think that's the issue.
What about
Deal.find(params[:id]) rescue nil
I recently decided I wanted to list all the users in my Ruby On Rails application - since I couldn't figure out how to list them any other way, I decided to use partials.
I have the following on my administration page (just hooked up to a its own administration controller):
<%= render :partial => User.find(:all) %>
I then have a file called _user.html.erb in my users view folder. This contains the following:
<ul>
<% div_for #user.object_id do %>
<li><%= link_to user.username, user.username %></li>
<% end %>
</ul>
When the application runs and I go to the administration page, I get the following error:
undefined method `id' for 4:Fixnum
It says it's because of this line (which is in the partial file):
<% div_for #user.object_id do %>
I'm unsure why this happens (and have googled for hours to try and find results and only find solutions that don't work for me). I think it's something to do with my usage of the #user instance variable, but I'm not totally sure.
You get that error because div_for expects an active record object as an argument, which it calls the id method on. You pass in a fixnum (the result of #user.object_id), which is not an active record object and does not have an id method.
So pass in #user instead of #user.object_id and it will work.
Also you should use user instead of #user, rails 3 does not set instance variables for partials anymore.
Lose the .object_id part. I seriously can't think why are you using object_id!Do you have a good reason for doing so? Anyway div_for wraps a div around an object, so leave the .object_id part!
instead of object you are using it's column or visa varsa you are using at that time you will get this kind of error.
Example
I am using id instead of user = User.first object.
Try this, it worked for me.
#item.unit_of_measure.name
instead of
#item.unit_of_measure_id.name