Reputation: 1000
I have created a function that collects all the entries of a model (called Nismo) that begins with a selected letter/number:
def showByLetter(letter)
@nismosByLetter = Nismo.all :conditions => ['substr(name,1,1) = ?', letter]
end
I have this inside my "Nismo" controller.
In my index view of the Nismo controller I have an alphabetical menu that I want to use to allow the user to select, for example, "B". This will then run the showByLetter function and then show in a page all the entries that start with that letter.
My problem is that in my index page I really don't know how to get this all to happen:
<% Array('A' .. 'Z').each do |letter| %>
<%= link_to letter, showByLetter(letter) %>
<% end %>
I am guessing I need to create a new view.html.erb file for this "showByLetter" function to display it's results in.
I have tried to get my head around it from the programatic programmers book and have seen comments on the net that might mean I need to play with the routes.rb file to add something like to get the route right:
namespace "nismo" do
resources :nismos do
member do
get :showByLetter
end
end
end
I am sure this is all very simple but I am confused and need some pointers.
any help would be appreciated!
Thanks
Adam
Upvotes: 0
Views: 68
Reputation: 86
In all honesty, the easiest way to do this would be in the index action in the 'nismo' controller. What you could do is change
<%= link_to letter, showByLetter(letter) %>
to
<%= link_to letter, nismos_path(:letter => letter) %>
What this does is creates a link back to the current index page and passes it a GET paramater similar to
yourrooturl.com/nismos?letter=A
And then in your index action in the Nismo controller, just add an if statement to determine if you should load all the nismos or just by the letter. Something similar to:
if params[:letter].nil?
@nismos = Nismo.all
else
@nismos = Nismo.all :conditions => ['substr(name,1,1) = ?', params[:letter]]
end
That should solve your problem and you won't have to deal with routes.
Upvotes: 1