Rails showing strange #<Game:0xb6783820> tag - ruby-on-rails

I have a simple page that displays some 'Games'.
Heres the code:
<ul>
<%= #tvshow.games.each do |game| %>
<li><%= game.gameTitle %></li>
<% end %>
</ul>
It displays like this:
The All-Syrup Squishee
#<Game:0xb6783820>
With the #Game tag coming AFTER the list item but before the closing list tag. Any idea why it's showing up or how I could get rid of it?

<%= outputs the result as markup, in this case an instance of the Game class.
For this kind of loop you want to use <% which executes some code but does not produce markup.
Edit line 2 to read <% #tvshow.games.each do |game| %>

Remove your first = from the line with the each
Rails is printing the result of the each statement, which returns the array itself. When you output an array, you will output the .to_s of each of its contents, which in your case is the default representations of the Game objects

Related

Rails 5 - rendering array defined in application_helper.rb

I want to use nhl_scores gem to get and display recent NHL game scores on the page. This is how I defined the method in app/helpers/application_helper.rb:
def scores
games = NHLScores::Games.new
s = []
games.recent.each do |g|
s.push("#{g.away_team} # #{g.home_team} - #{g.away_team_score}:#{g.home_team_score}")
end
s
end
And this is how I display this array:
<ul>
<%= scores.each do |s| %>
<li><%= s %></li>
<% end %>
</ul>
The result is:
pic with result
Yeah, for some reason the full array gets displayed after the last closing li tag but before the closing ul tag. How do I remove it? Should I define the method that returns this array elsewhere?
Try this
<ul>
<% scores.each do |s| %>
<li><%= s %></li>
<% end %>
</ul>
The <%= %> is displaying the entire scores array again which you dont want(<%= %> causes the value to be displayed).
Don't use <%= to output the result of scores.each, which is scores.
You're outputting the <li> tags inside the .each block, and then when the .each is done, the value returned from each (scores) is being passed to <%= which echos it to the browser.
You need to be aware of when to use <% and <%=; in this case, you need <%.

In a rails view, how can I send output to view besides <%= %>?

Short version:
It seems weird to me to have rails code like, say,
<% if #list.empty
%><%= val %><%
end %>
Is there some way to do something like this?
<% if #list.empty
some_display_function_i_wish_existed val
end %>
Long version:
I have a model, tweet.rb, that overrides to_s. The to_s works fine.
I have a view that needs to output to_s for each tweet in #meme.tweets .
I've observed the following:
<% #meme.tweets.each do |tweet|
tweet
end %>
Result: no output
<% #meme.tweets.each do |tweet|
puts tweet # or tweet.to_s does the same thing
end %>
...Result: no output
<%= #meme.tweets.each do |tweet|
tweet
end %>
...Result: output is entire inspection of each tweet, not to_s
<%= #meme.tweets.each do |tweet|
puts tweet # or tweet.to_s does the same thing
end %>
...Result: output is entire inspection of each tweet, not to_s
<% #meme.tweets.each do |tweet| %>
<%= tweet %>
<% end %>
...Result: works as intended (outputs result of to_s for each tweet). So does:
<%= #meme.tweets.collect do |tweet|
tweet.to_s
end %>
...Result: works as intended.
I come from a PHP background, and don't really understand the rules here.
I know I can do it the way I did in the last example.
But could someone explain why none of the other examples work as I intend?
It seems to me that the rules APPEAR to be:
1) <%= something %> will take that thing, call to_s on it, which will default to inspect if not overridden.
2) <% something %> will execute something
Is there a way to use 2) <% %> to send output to the view?
Or is it against the rules to have <% %> tags that span multiple lines of ruby code at all?
<%= code %> will print to the the output the result of the inner code. <% %> won't print anything, it just evaluates the inner code.
That's why the first example doesn't work. On the second example you expect the puts to print the tweets, but puts doesn't print on the same buffer... (you'll see the tweets printed on the rails console instead).
On 3rd and 4th example you are printing the collection as an object (#meme.tweets.each returns an Enumerable and ERb call #to_s on that) and not the code inside the block.
The 5th form is correct. That's what you'll normally do.
The 6th form is in some way correct too. There you are iterating a collection, calling #to_s on each element and then collecting them on a new array, that gets printed to the output (but you are printing an array of strings, not just one big string).
you can get a similar result with #join. (It returns a string created by converting each element of the array to a string)
<%= #meme.tweets.join %>
<% %> are used when you do not want the Ruby code you're executing to output anything. The <%= %> tags are used when you want to output something. This is why your example using <%= %> and tweet.to_s works as intended.
If you don't specify which attribute you want to output, then yes, puts will display the whole object. If for example, you had a message attribute on your tweet object, writing tweet.message (inside of a <%= %>, of course) would output just the message attribute of that tweet.
The direct answer is the concat function, eg:
Hi, my name is <% concat("Shelvacu") %>.
which is the same as
Hi, my name is <%= "Shelvacu" %>.
Which both output Hi, my name is Shelvacu.
Think of it like this: An erb template is parsed, transformed into valid ruby code, and then that ruby code is run*. Everything that is not inside <% ... %> is converted to concat("..."), <% statement %> is converted to statement, and <%= statement %> is converted to concat(statement.to_s).
So when ERB sees
1 + 2 = <%= 1 + 2 %>
<% puts "hello" %>
<% #meme.tweets.each do |tweet| %>
<%= tweet %>
<% end %>
that code is then translated to*
concat("1 + 2 = ")
concat((1 + 2).to_s)
concat("\n\n")
puts "hello"
concat("\n\n")
#meme.tweets.each do |tweet|
concat(tweet.to_s)
end
* This is an oversimplification, ERB does much more so that errors point the right line, statements don't merge with eachother in unexpected ways, and I didn't even mention <%- ... %>. However, this should be a decent mental model for understanding whats happening when you write code in ERB.

Ruby How to display message if include? statement is true or false

I'm very new to Ruby and am attempting to display one of two messages based on whether certain words are included in an array. My current controller contains the following:
#cookie = ["gluten", "sugar", "dairy", "chocolate"]
And my view contains this:
<%= #cookie.include?"gluten" %>
The above returns 'true' and prints on the page just fine. However, nothing gets printed on the page when trying either of the following methods. The page renders fine with no errors, but no messages:
<%= puts "Sorry" if #cookie.include?"gluten" %>
and
<%=
if #cookie.include?("gluten")
puts "Sorry, you cannot eat this."
else
puts "You have the greenlight."
end
%>
I'm hoping that I'm creating a very simple mistake in syntax or am misunderstanding the usage of the include? function.
looking at the ruby it appears to be sound, http://rubyfiddle.com/riddles/d6798.
Must be rails error so try
<% if #cookie.include?("gluten") %>
<%= "Sorry, you cannot eat this." %>
<% else %>
<%= "You have the greenlight." %>
<% end %>
If you want it all in one erb statement, you would do something like this:
Don't use "puts". The "<%=" is already doing a 'to_s' and will output the value to the response body. You may have seen the results show up in your logs if you used 'puts'.
Also - for erb, the <% ... %> syntax, that is for logic, often an 'each' or 'if' state, the <%= %> is for writing to the screen. Most of the time it is the attribute of a ruby object like <%= user.name %>

Rails prints string when each is used in html.erb

While it could of course be done neater by putting the code into the controller or something, I can not image why the following is happening:
assume that #some_table.some_text contains 5 lines.
putting the following code in my html.erb file:
<% #some_table.some_text.lines.each do |cur_line| %>
foo
<% end %>
results in 5 foos followed by all the lines in #some_table.some_text.
I could imagine this would happen when using the <%= %> but not with <% %>.
Obviously, I don't want the #some_table.some_text to be shown.
What am I doing wrong here?
That's just the way that the Ruby lines method works - it returns an Enumerable, which can't be looped through in the same way. For your purposes, try
<% #some_table.some_text.split(/\n/).each do |cur_line| %>
instead.
Alternatively convert the Enemerable into an array before calling each, using one of the methods, eg:
<% #some_table.some_text.lines.collect.each do |cur_line| %>

Odd Output with Rails each loop

I have a view that for some reason displays the memory location of the object I'm trying to loop through. I'm kinda new at rails, so I'm unsure why this is happening. The object is a note with two fields, title and content.
In the controller I have (in the index function)
#note = Note.all
Then in the view I'm doing this
<%= #notes.each do |note| %>
<%= link_to note.title, "notes/#{note.id}"%>
<% end %>
The output in the browser is
School Work #Note:0x1042e4708>#Note:0x1042e2ae8>
Thanks for the help
rather than:
<%= #notes.each do |note| %>
use:
<% #notes.each do |note| %>
wrapping ruby in <%=%> will always output something to the view, drop the equal sign (<%%>) to simply execute ruby without outputting

Resources