Reputation: 618
I have generated a "Talks" scaffold for a yearly conference. Each talk consists of a name, title and the year it occurred.
I want to display only the talks from one specific year at a time.
In the app/views/talks/index.html.erb file I can do this with:
<% @year = 1978 %>
<% @talks.where(:year => @year).each do |talk| %>
Which will then list only talks from 1978.
I am also listing the years in which talks occurred in the sidebar (same file) using:
<ul>
<% Talk.uniq.pluck(:year).each do |year| %>
<li><a href="" ><%= year %></a></li>
</ul>
Which gives a list of years like:
I want the user to be able click on a year to show only talks from that year.
Is there a way to set the @talks variable via the url?
Something like:
<li><a href="/talks?year=1978" ><%= year %></a></li>
Or is there a better approach?
Upvotes: 0
Views: 698
Reputation: 1988
In your controller:
def index
@year = params[:year].to_i
@year = 1978 if year < 1978
@talks = Talk.where(:year => @year).to_a
end
Remove <% @year = 1978 %>
in your view.
Replace <% @talks.where(:year => @year).each do |talk| %>
by <% @talks.each do |talk| %>
Upvotes: 1