Question with .find and a return value - ruby-on-rails

I'm fairly new to rails (only about a month's experience), so this may be trivial. In my app, if I call
<%= Group.find(:all).each do |g| %>
<p><%= g.name %></p>
<%= end %>
it prints out all of the groups' names correctly. However, afterwards, it returns all of them (with the hexcodes, and stuff). I figure that's because .find returns everything you have it iterate over. Anyways - on to my question: Is .find the wrong method, or how do I go about iterating over every Group, without returning them afterwards?
I would appreciate any help or insight you all have.
Thanks!

I'm guessing you're doing something like
<%= Group.find(:all).each do |g| %>
<p><%= g.name %></p>
<%= end %>
That would print the return value of the whole statement. Instead, do this
<% Group.find(:all).each do |g| %>
<p><%= g.name %></p>
<% end %>
That wouldn't print the returned value.
Sidenote: Group.find(:all) is the same as Group.all

Related

How to handle the checkbox with two array and if in one array user on-click the checkbox that should append in second array

#complete[] and #incomplete[] are two array then I need to used with these array with checkbox complete array is by default true and incomplete by default false .
<%= form_with(model: #task, local: true) do |form| %>
<% #complete = Array.new %>
<% #incomplete = Array.new %>
<% #tasks.each do |task| %>
<% if task.complete != false then %>
<% #complete << task.name %>
<% else %>
<% #incomplete << task.name %>
<% end %>
<% end %>
<!-- complete task -->
<%= #complete %>
<!-- incomplete task -->
<%= #incomplete %><br>
<% #complete.each do |i| %><div id = "task_check">
<%= form.check_boX "#incomplete[]", incomplete.id %>
<%= form.check_box "chkbox_ary[#{i}]" , {checked:true} %>
<%= form.submit "update"%>
<%= content_tag(:strike, i)%>
<br></div>
<% end %>
<br> <hr>
<script>
<% #incomplete.each do |i| %>
<%= form.check_box "chkbox_ary[#{i}]" %>
<%= form.submit "update"%>
<%= i %><br>
<% end %>
<% end %>
If I check the box as false in complete then it should append to array called complete and if I check the box true in incomplete then it should append to second array called complete.
if I may, I'd like to point out some stylistic issues in your code first:
it is unusual to compare with false, i.e., if task.complete != false should be just if task.complete this works thanks to the concept of Truthiness in Ruby
you can just leave off the then in an if-conditional, that's what most Ruby developers do, i.e., if task.complete then can just be if task.complete
view templates (.erb files) should contain as little logic as possible, i.e., extract the creation of the #incomplete and #complete arrays into your controller or some other place
Ruby Enumerable has many methods to make common work easier, for instance splitting a collection into two collections can be done with partition, i.e., you can do #complete, #incomplete = #tasks.partition(&:complete) to populate the complete and incomplete arrays (&:complete is a shorthand for { |task| task.complete }, google Ruby symbol to proc if you want to know more about it)
I'm not sure I understand your question as it is. At the time the complete and incomplete arrays exist no user interaction takes place. I.e., nobody can click anything. When the HTML is rendered, no arrays exist anymore.
So there's two ways I can interpret your question:
You wish to move the DOM elements around => you need to use JavaScript for that
You wish to partition the checkboxes when the form is submitted => you need to show us the code in your controller that handles the form-submit for us to help you out
Which is it?
PS: I know this isn't an answer right now, but I could not write this as a comment since it's too long and a comment would have been illegible.

Rails for Date format issue

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/

Is there a way to get the console to ignore certain errors?

Say I have an instance variable #n, and I'm calling <%= #n.title %> in my view.
If #n equals a valid record, then this will print normally. But if #n is blank or invalid, then the entire page will show an error message, because of this one little line.
Is there a way to get #n.title to just print nil if #n is nil or invalid?
I'm looking for a way to do this without conditional statements. For example, if I wanted to print
<%= #v1.title %>,<%= #v2.title %>,<%= #v3.title %>,<%= #v4.title %>,
if I wanted to use conditionals to print without errors, it would require 12 lines of code:
<% if #v1 %>
<%= #v1.title %>,
<% end %>
<% if #v2 %>
<%= #v2.title %>,
<% end %>
<% elsif #v3 %>
<%= #v3.title %>,
<% end %>
<% elsif #v4 %>
<%= #v4.title %>,
<% end %>
It seems a shame to use 12 lines on this. It would be nice to be able to accomplish the error-handling right when printing.
You can totally do this easily with the try() method. I use it all the time.
<%= #n.try( :title ) %>
That will return nil if #n is nil or if the title method doesn't exist on #n.
You can also chain them together like this:
#n.try( :title ).try( :to_s )
Or even use it on a hash:
#n.try( :[], 'name' ) # Which is the same as #n['name']
See http://api.rubyonrails.org/classes/Object.html#method-i-try
EDIT (Jan 11, 2016)
You can now use the "safe navigation operator" as of Ruby 2.3.0.
#n&.title&.to_s
As well as the Array#dig and Hash#dig methods introduced in Ruby 2.3.0.
hash = { 'name' => 'bob' }
hash.dig( 'name' ) # Which is the safe way to do hash['name']
You can add some logic to your view that differentiates between development (where some errors can be ignored) and production environments (where errors should cause your app to fail in an obvious and ugly manner). Ruby's nil has a "falsey" nature, so you can use that concept to your benefit as well.
<% if Rails.env.development? %>
<% if #n %>
<%= #n.title %>
<% else %>
<%= nil %>
<% end %>
<% else %>
<%= #n.title %>
<% end %>

Rails instance variable join

This is so simple but it's been ages since I needed this.
I have the following code
<% #miniature.minisets.each do |miniset| %>
<%= link_to miniset.name, miniset %>
<% end %>
It outputs Minisetname Minisetname Minisetname etc
I want it to output Minisetname, Minisetname, Minisetname with commas.
I've tried to include .join(", ") but can't find the right place to put it. Do I also need to use .map instead of .each?
Ignominy.
Here's one way that ought to work:
<%= #miniature.minisets.map { |miniset| link_to miniset.name, miniset }.join(", ").html_safe %>

Rails - Display inline rails errors

How can I condense my code into a single statement:
<% #policyholderdetail.errors.each do |attr,msg| %>
<% if attr == :title %>
<li><%=attr %> <%= msg %></li>
<% end %>
<% end %>
I would like to show only the errors for :title next to the field but feel there should be a better statement to do this as opposed to looping through all of the errors until I get to the one I want.
Question - can I condense the first two lines into one better statement?
You can write: #policyholderdetail.errors[:title]. See here.
Use
<% if #policyholderdetail.errors[:title].present? %>

Resources