Been trying to set up a regular blog in Ruby on Rails, and finally got the comment system to work within a post. However, when I loop through each comment and try to output the comment's title it displays this,
awef [#<Comment id: 6, title: "awef", link: nil, campaign_id: 5, user_id: 1, created_at: "2015-09-24 09:46:43", updated_at: "2015-09-24 09:46:43">]
Instead of just the title. How can I fix this?
The loop in your view should be something like this:
<% #blog.comments.each do |f| %>
<%= f.title %>
<% end %>
Please check you are using the right angular parenthesis (<%= %>) and not placing p puts or inspect commands inside them.
Edit:
Now that you show use the code, the problem is in the first angular parenthesis: should be <% not <%=. The first is for the logic, the latter to output erb code.
<% #blog.comments.each do |f| %> # remove "="
<%= f.title %>
<% end %>
<% ... %>: Executes the ruby code within the brackets
<%= ...%>: Executes the ruby code and show the executing result in webpage
Classic mistake, it's because you're using <%= ERB output tags for the .each loop. You can view more information on how to write correct ERB here.
You need to replace your <%= output tags with standard ERB tags <%:
<% #blog.comments.each do |f| %>
I was stung by that one myself when I was starting out.
The problem you have is probably the = in your each statement.
Try to use this:
<% #blog.comments.each do |f| %>
<%= f.title %>
<% end %>
Notice the removed = at <% #blog.comments.each do |f| %>
The reason is as the <%= %> always prints while <% %> only executes the code.
Related
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 %>
I have a segment of code:
<% #public_address.each do |key| %>
<%= key["address"]["address"] %>
<% end %>
This displays the keys properly, but this code
<% #public_address.each do |key| %>
<% puts key["address"]["address"] %>
<% end %>
displays nothing. What gives? What's the difference between the two?
The <% %> and <%= %> are used in erb to execute ruby code when rendering a template.
Erb is the default template engine in rails.
Difference between <% %> and <%= %>
<% %> Will evaluate the ruby code it contains, but "silently".
Meaning that no output is going to be printed on the rendered page.
<%= %> on the other end, evaluates the ruby it contains and
renders the result on the rendered page.
What's the difference between <% code %> and <%= code %> in Rails erb?
What's puts?
Puts is simply a method from Ruby that is used to print a string at runtime. It has nothing to do with erb templates.
In your first bit of code <%= key["address"]["address"] %>, the <%= %> is rails syntax for evaluating the code inside and returning the value.
In your second bit of code <% puts key["address"]["address"] %>, you use <% %>, which doesn't return an evaluated rails statement. Furthermore, puts is a method that outputs whatever follows it to the stout object. In a command line program, that means printing out to the terminal screen, but in a web app you aren't working with a terminal screen. You are working with controllers and view templates, so it is necessary to use the evaluative <%= %> if you want to return values that will be displayed in the view.
I was trying to refactor my erb code for rating stars into one line and came across this, is it possible to achieve the results another way?
So currently it's like this
<% rating.times do %>
<%= image_tag 'rating_star.png' %>
<% end %>
Ideally I'd like to reduce this to
<%= rating.times { image_tag 'rating_star.png' } %>
This returns the value of rating (0, 1, 2, 3, 4 or 5), if I change <%= to <% nothing is rendered. Is there any way to do this?
You can use concat:
<% rating.times { concat image_tag('rating_star.png') } %>
But <%= ... %> within a loop is cleaner IMO.
You need #map to return an array of all image_tags you wish.
Then #join the result to get a string.
Lastly, you need to tell this string is valid html with #html_safe.
<%= rating.times.map{ image_tag 'rating_star.png' }.join.html_safe %>
The difference between <% %> and <%= %> is that the former is simply evaluated, but with the latter the result is rendered. You have two things going on in your code snippet: the control part (the loop), and the rendering part (the image tag). Since you want only the image tag part rendered, you want to surround only that code with <=% %>, and the rest with <% %>.
So while this would work:
<%= rating.times { %> <%= image_tag 'rating_star.png' %> <% } %>
I find it much less readable than the 3-line version.
In the Rails views, I regularly find lines like:
<%= my_var %>
What if I had a slightly more complex situation and I needed to trigger the printing with plain code instead of <%= %>?
Example:
<% .....
puts my_var
%>
I guess is a silly question but bear with me, I'm a ruby beginner.
Look at documentation of ERB
In <% %> you put expressions that are not for printing out.
In <%= %> you put code for printing out.
Example:
<% if #cost < 10 %>
<b>Only <%= #cost %>!!!</b>
<% else %>
Call for a price, today!
<% end %>
You can use helper method which is much more cleaner.
If I write something like:
<% if signed_in?.blank? %> or <%= link_to "Sign Up", sign_up_path %>
What is the difference between the two signs of <% and <%=?
Why make it this way instead of using just one for simplicity?
When do I know I need to use <% over <%=?
<%= puts the return value of the code inside to the page.
<% just execute code.
Here is the good guide about ERB http://api.rubyonrails.org/classes/ActionView/Base.html
<% %> Simply executes the statement(s) inside that block, whereas <%= %> will output the result of the statement.
So for example, with the <% if signed_in?.blank? %>, the ruby interpreter just executes that code and checks if signed_in is blank.
The <%= link_to %> statement will actually generate HTML.