1

New to ruby/rails so please bear with me.

I executed a query and stored it in a @variable located in my controller. In my view I want to output the results as a list, as so:

Controller:

def new
  @content = OrientationContent.where("site_id in (?)", [0, session[:site_id]])
end

View:

<%= @content.each do |c| %>
<ul>
    <li><%= c.content %></li>
</ul>
<% end %>

However, my output comes out as so:

Check 1
Check 2
Check 3
Check 4
Check 5
Check 6

[#<OrientationContent id: 17, site_id: 0, content: "Check 1", created_at: "2014-12-26 03:46:25",
updated_at: "2014-12-26 03:46:25">, #<OrientationContent id: 18, site_id: 0, content: "Check 
2", created_at: "2014-12-26 03:46:25", updated_at: "2014-12-26 03:46:25">

I intentionally cut off the output at the very end since it's a bit long. But it does this for all Check items from 1 to 6.

More so, when I do (1..5) each do |c|

it will output numbers 1 to 5 and at the end it will also output "(1..5)"

My question is how do I keep the first part of the output but not the second half (in my first example, I don't want the records outputted. In my second example, I don't want the "(1..5)" to show.

1 Answer 1

4

The Fix:

<% @content.each do |c| %>
<ul>
    <li><%= c.content %></li>
</ul>
<% end %>

#each method returns the collection after its completes it iterations. And <%= always executed the Ruby code and then print the result, but <% executes the code, but never prints. But in your code, you enable ERB to print the result of the collection, that's why you are getting what you don't want to get. That's why adapt my fix to prevent the printing, but execute only.

Sign up to request clarification or add additional context in comments.

1 Comment

Always the small things, thank you Arup! I will accept answer in 11 minutes!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.