简体   繁体   中英

Ruby/Rails: Iterating through ActiveRecord Query Results Using Blocks?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM