I have a loop to getting values in my database, but when I'm trying to get a value from a relationship, I get an error:
undefined method `first_name' for nil:NilClass
This is the loop:
<%= #sample.each do |s| %>
<%= s.relation.first_name %>
<% end %>
when I tried
<%= s.relation.to_json %>
with .to_json, I get this:
{"first_name":"testingtwo","last_name":"fdsaf","updated_at":"2013-11-21T07:47:05Z","user_id":null}
Shouldn't s.relation.first_name work?
Thanks
it's possible that there is a relation in the loop that doesn't have a value, and is getting hung up there - try this:
<%= #sample.each do |s| %>
<%= s.relation.first_name if s.relation %>
<% end %>
this only outputs s.relation.first_name if it isn't nil. You could also try this:
<%= #sample.each do |s| %>
<%= s.relation.first_name || "No name given" %>
<% end %>
which puts the first name if it exists, or "No name given" if it doesn't
One important thing you may want to consider too is whether or not having nil values within your database for that particular relationship is valid to begin with.
The || solution proposed is definitely a good one and a great Ruby pattern, but it may be worth adding in an ActiveRecord validation to ensure your relation(ships) are never nil.
ActiveRecord Validations are definitely the way to go in that particular case.
Related
I am trying to output just the date on the generated line, but when I execute this code, which I am sure is not elegant at all, it gives me undefined method 'strftime' for nil:NilClass
<% #person.subordinates.each do |sub| %>
<tr>
<td>
<% if sub.position == 'alumni' %>
<p>
<%= link_to(sekret_person_path(sub.position, sub.user_name)) do %>
<strong><%= sub.fname %> <%= sub.lname %>,</strong>
<% end %> <%= sub.startdate.strftime("%Y") %> - <%= sub.graddate.strftime("%Y") %>
</p>
<% end %>
</td>
</tr>
<% end %>
Further up in my code, I am using #person.startdate.strftime("%m/%d/%Y") without any issue, but I think my issue is that I am using the sub call, which is grabbing any people that are flagged as sub to this person.
Your error says that one of your attributes is nil. The sytax is correct. Try debugging with:
#person.subordinates.select { |sub| sub.startdate.nil? || sub.graddate.nil? }
The elements that are retrieved on this line will be the ones that are giving you errors, because you are trying to run nil.strftime('%Y'), which makes sense.
You should use a condition on your .erb to stop it, like:
<%= sub.startdate && sub.startdate.strftime("%Y") %> - <%= sub.graddate && sub.graddate.strftime("%Y") %>
It is not an error with Rails.
strftime is being called on nil object. Make sure you are calling strftime on a date, time, or datetime object.
Refer to strftime on rails apidock - https://apidock.com/ruby/DateTime/strftime
Another way to solve this that will guard against nils would be:
<%= sub.startdate&.strftime("%Y") %> - <%= sub.graddate&.strftime("%Y") %>
That way you don't have to add a conditional to make sure that any method/attribute in the chain exists prior to calling them. This works because of the safe navigation operator, which is explained in depth here: https://rubyinrails.com/2017/11/17/safe-navigation-operator-ampersand-dot-in-ruby/
I am have a instance variable ride that comes from a table and it has a column ride.pickup_at
If I do <%= ride.pickup_at.class.name %> I get
time
So Strftime should be available.
Now, if I do <%= ride.pickup_at.strftime('%x') %> I get an error
undefined method `strftime' for nil:NilClass
What do I have to do to make strftime available?
you can use try to do the nil judge: <%= ride.pickup_at.try(:strftime, '%x') %> .Or I think you should figure out what to do if ride.pickup_at is nil
You can add a if condition like this before your code like this.
<%if !ride.pickup_at.nil? %>
<%= ride.pickup_at.strftime('%x') %>
<% end %>
This might be because of some record having nil value for pickup_at
so I have a standard has_many through association in my models, very similar to the question here: Loop through ActiveRecord::Associations::CollectionProxy with each
I used the advice in that problem but I think I am having some trouble getting it through on my ERB file so that it shows up in my app. At the moment I have the following:
<%= #memberships.map do |a| %>
<%=a.name%>
<% end %>
In this scenario, the membership model is the one through which users and organizations have many though (#memberships = #user.organizations). So the #memberships.class returns
ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_Organization
on the rails console. So the moment, in the browser the code returns on a page where the user is in two orgs:
orgone orgtwo["\n", "\n"]
I just don't know how to manipulate the proxy classes to return what I want. Thanks!
UPDATE:
I figured it out, I had to remove the = at the top of the block, and I added some styling with a comma:
<% #memberships.map do |a| %>
<h3><%=a.name %> <%= ", " unless a == #memberships.last %></h3>
<% end %>
If you want to print the name of each membership, what you want is
<% #memberships.each do |membership| %>
<%= membership.name %>
<% end -%>
The <% prefix in ERB executes code without appending the results to the output buffer, while the <%= prefix outputs the string representation of the result of the expression. Since each returns an enumerator, a <%= will return the string representation of the enumerator which is something like #<Enumerator:0xDEADBEEF.
I'm trying to use sort on each do. I get the error
wrong number of arguments(1 for 0)
I understand that I cannot daisy chain them together. Does anyone know another methods of getting this done.
<% Category.sort(:id).limit(4).each do |type| %>
<%= type.name %>
<% end %>
The result I am aiming for is to have all categories listed from a to z.
Assuming the Category is an Active Record then
<% Category.order(:id).limit(4).each do |type| %> would do the trick.
On my user profile page in my rails app, I am recieving the error:
undefined method `title' for nil:NilClass
I know it is because of the following 3 lines of code:
<% if #user.profile.title %>
<%= #user.profile.title %>
<% end %>
I don't understand why. Since i use the if statement, shouldn't it first check whether title exists, then if it exists display it, and if it does not exist, it should not display it. What is wrong and how do I fix it? Thanks.
Since title is nil you can't test against it like you did.
Try:
<% if #user.profile.try(:title) #user.profile.title %>
You can do:
<% if #user.profile.present? %>
<%= #user.profile.title %>
<% end %>
Or with try:
<%= #user.profile.try(:name) %>
With a default value if no profile associated:
<%= #user.profile.try(:name) || 'No profile for this user' %>
Because it is not correctly. If you want to get access to some parameter from user you have to use direct access. But if you want to use profile that belongs to User model look at this
link