I am trying to loop through records in a db and pull out a particular
field. I have no problem with the code when I run it in the console;
however when I try to transfer the code to my Rails environment it
fails.
The code I'm using in my console is:
show = Schedule.find(:all)
n = show.size - 1
0.upto(n) { |i| puts show[i].venue }
The above code runs perfectly. To adapt this code for Rails, I am doing
the following:
(IN THE CONTROLLER)
class ScheduleEditController < ApplicationController
def index
@show = Schedule.find(:all, :order => 'date ASC')
end
end
(IN THE VIEW)
<ul>
<%= render :partial => 'shows' %>
</ul>
(IN THE PARTIAL)
<% n = @show.size - 1 %>
<li><%= 0.upto(n) { |i| puts @show[i].date } %></li>
The result I get is this:
<ul>
<li>0</li>
</ul>
The result I am looking for is:
<ul>
<li>2</li>
<li>3</li>
<li>1</li>
</ul>
Yes, I am obviously a noob. Please help shed light on where I've gone
wrong before I tear all my hair out.
(IN THE PARTIAL)
<% n = @show.size - 1 %>
<li><%= 0.upto(n) { |i| puts @show[i].date } %></li>
When you have a n erb output block (<%= ... %>) what appears in the
view is what the expression evaluates to. calls to puts inside there
are immaterial n.upto evaluates to n, hence the result you're getting
You need something like
<% 0.upto(n) do %>
<li><%= @show[i].date %> </li>
<% end %>
That's not a very idiomatic way of doing it though. More idiomatic
would be
<% @show.each do |show| %>
<li><%= show.date %> </li>
<% end %>
or using a partial (although it might be a bit overkill in this
particular case)
I am trying to loop through records in a db and pull out a particular
field. I have no problem with the code when I run it in the console;
however when I try to transfer the code to my Rails environment it
fails.
The code I'm using in my console is:
show = Schedule.find(:all)
n = show.size - 1
0.upto(n) { |i| puts show[i].venue }
The above code runs perfectly. To adapt this code for Rails, I am doing
the following:
(IN THE CONTROLLER)
class ScheduleEditController < ApplicationController
def index
@show = Schedule.find(:all, :order => 'date ASC')
end
end
(IN THE VIEW)
<ul>
<%= render :partial => 'shows' %>
</ul>
(IN THE PARTIAL)
<% n = @show.size - 1 %>
<li><%= 0.upto(n) { |i| puts @show[i].date } %></li>
The result I get is this:
<ul>
<li>0</li>
</ul>
The result I am looking for is:
<ul>
<li>2</li>
<li>3</li>
<li>1</li>
</ul>
Yes, I am obviously a noob. Please help shed light on where I've gone
wrong before I tear all my hair out.
First change your @show to @shows (it has more than one, so for readability, make it plural)
Second, change your partial to _show, not _shows.