Ruby On Rails, code in each loop in view - ruby-on-rails

I have a little problem...
My View:
--html---
<% #things each do |thing| %>
<% other = #others.find_by(:ID == thing.ID)%>---->it runs just once. Why?
<div>
<p>thing.ID</p> ---------------> This is correct.
<p>other.NAME</p> -------------> But it isn't. It is always same (fisrt value..).
</div>
<%end%>
--html--
I like this, that the other.NAME changes too. Thanks for the help!

You have == when you need =>
:ID == thing.ID is evaluated to false, which leads to:
#others.find_by(false) which happens to return the first record every time.
Also, your naming of attributes is not standard - by rails convention they should be small letters: other.name

you can used following query to find 'other'
other = #others.find_by_ID(thing.ID)
if record not found it will return 'nil' and not 'record not found' error.
You can used
other.try(:NAME)
other.name will give error if 'other = nil'.

Related

If, else dynamic statement logic

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 %>

How do I check if a variable is defined in rails?

<% if dashboard_pane_counter.remainder(3) == 0 %>
do something
<% end>
If dasboard_pane_counter wasn't defined, how can I get this to evaluate to false rather than throw an exception?
<% if defined?(:dashboard_pane_counter) && dashboard_pane_counter.remainder(3) == 0 %>
# do_something here, this assumes that dashboard_pane_counter is defined, but not nil
<% end %>
When using rails and instance variables, nil has a try method defined, so you can do:
<% if #dashboard_pane_counter.try(:remainder(3)) == 0 %>
#do something
<% end %>
so if the instance variable is not defined, try(:anything) will return nil and therefore evaluate to false. And nil == 0 is false
local_assigns can be used for that, since this question is from a few years ago, I verified that it exists in previous versions of rails
<% if local_assigns[:dashboard_pane_counter]
&& dashboard_pane_counter.remainder(3) == 0%>
<% end %>
It's in the notes here
http://apidock.com/rails/ActionController/Base/render
Posting this answer for beginner coders like myself. This question can be answered simply using two steps (or one if using &&). It is a longer and less pretty answer but helps new coders to understand what they are doing and uses a very simple technique that is not present in any of the other answers yet. The trick is to use an instance (#) variable, it will not work with a local variable:
if #foo
"bar"
end
If #foo is defined it will be return "bar", otherwise not (with no error). Therefore in two steps:
if #dashboard_pane_counter
if #dashboard_plane_counter.remainder(3) == 0
do something
end
end
Another way, with a neat gem, is 'andand.'
https://github.com/raganwald/andand
Insted of
if !var.nil?
I would use
unless var.nil?
Thats much better ruby code!

Rails: undefined method error not fixable with attr_accessor

I have created a very simple model called Discussion and one of the columns is a boolean called resolved. The idea being that once a discussion item has been resolved that value is set to true.
On the edit form, I tried to put in some logic based on the value of that field.
<%= form_for(#discussion) do |d| %>
...
<% if d.resolved == "true" %>
<p>The discussion is resolved</p>
<% else %>
<p>The discussion is not resolved</p>
<% end %>
<% end %>
However, I'm getting an error message
undefined method `resolved' for #<ActionView::Helpers::FormBuilder:0x00000101674678>
I tried adding an attr_accessor line to my model but that didn't do anything for me either. I'm not sure what I have to do to fix this. I'm pretty new to rails, so I'm sure that whatever the problem is it's probably pretty simple to fix, but I just don't get it. Thanks.
Because d represent an instance of the form builder, you want
<% if #discussion.resolved %>
If resolved is represented as a "boolean" in ActiveRecord.
every boolean column represents as predicate, so you can use:
if #discussion.resolved?
...
end
What you're looking for is the resolved? method.
<% if #discussion.resolved? %>
which is auto-generated for boolean columns.

Count Method on Undefined Active Record Array #objects.count

Is there a way to write a clean if nil then in a view. Assuming my lack of ruby is biting me here. Example,
If object nil, then return, nothing found
have
<%= #objects.count if #objects %>
want something like this
<%= #objects.count if #objects then "nothing found" %>
There are many ways to write something like this.
Something simple would be:
<% if #objects %>
<%= #objects.count %>
<% else %>
nothing found
<% end %>
If you get into a slightly more complex conditional I would suggest moving the logic into a helper and call it from the view. ex:
<%= count_for(#object) %>
Here's a good solution for you:
<%= "nothing found" unless #objects.try(:length).to_i > 0 %>
One of the issues is that you can't run count on a nil object. Therefore you need to use Rails' super handy .try() method to return nil when #objects = nil, rather than NoMethodError.
Next issue: You can't make a comparison between nil and a number using > so you need to convert the results of #objects.length to an integer which will return 0 for nil.
Lastly, try calling length rather than count. This will avoid running any extra queries when #objects is defined.
Avoids: SELECT COUNT(*) FROM 'objects'
Also if you want to display the count using this one-liner technique you can simply write up a shorthand if/else statement as follows:
<%= #objects.try(:length).to_i > 0 ? #objects.length : "nothing found" %>
One last option:
Use the pluralize method, which can handle a nil count:
Showing <%= pluralize( #objects.try(:length), 'object' ) %>
Sorry, I know this is pretty late, but hopefully helpful for someone else!

Simple Rails Conditional Statement

Pretty simple I'm sure... but I can't figure out why it wouldn't work.
<tr<% if film.viewed == true %> class="viewed"<% end %>>
The film.viewed is a boolean but its not rendering the class if its true. Probably a syntax error. Any help? Also is there an easier way to write this without opening and closing? I tried using:
<tr<% if film.viewed == true puts class=\"viewed\" end %>>
Again probably a syntax error. I'm coming from PHP so I'm still learning.
Thanks.
Your best bet would be something like the following...
<tr <%= 'class="viewed"' if film.viewed? -%>>
All boolean ActiveRecord columns get a question mark method that will return a true or false. As MySQL stores booleans as 1/0, I usually use the question mark method just to be safe.
I think this is easer to read:
<%= content_tag(:tr, "", :class => film.viewed? ? "viewed" : nil) %>
I'm guessing film.viewed isn't true, but another value.
try something to the effect of
<tr <%= "class='viewed'" if film.viewed %> >
<tr <%= film.viewed ? 'class="viewed"' : 'class="notviewed" %> >
So, some notes.
To do a full if ... end you would have needed a ";" or newline before the end.
Do you actually have a local variable or parameter called film?
You need <%= and not just <% in order to interpolate the final result of your template code.
I imagine the erb template driver calls the to_s method on whatever result it gets, and since nil.to_s returns "" then you are safe with a stand-alone false if statement, which has the effect as an expression of returning nil. But somehow having the expression always return a value one would be willing to see interpolated would seem to make sense.
I would rather do something like this.
<tr class="<%= film.viewed ? "viewed" : "" -%>"></tr>

Resources