Reputation: 47
I am relatively new to rails and using rails 3. I am trying to create an online glossary so that if a user clicks 'A' on the menu they will be shown entries from that database that all start with 'A'.
I know that you can do this using different pages such that you can have a 'letter_A.html.erb' file and 'letter_B.html.erb' file etc but I'm wondering if it can be done in the same file since I want to avoid repeating the same code over and over?
What I would like is if the user clicks on the link 'D' they may be taken to another page 'letter.html.erb' but only see the entries that begin with 'D'. And if they click 'A' they again get taken to the same page but only see entries starting with 'A'. I think you have to pass in a variable into the link_to function but I'm not sure how to do this.
Any help would be much appreciated.
Thanks in advance.
I have created a method inside my posts controller like so:
def showletter
@posts = Post.where(:letter => "B")
...
end
and that shows up all entries that start with the letter B for example. But what I am wondering is can you pass a variable into your controller so that the "B" can be replaced by a variable that will be between A..Z? From this I was hoping to use link_to_function or something similar in my view and call the same method for different links? I'm still new to rails so I'm not sure if this can be done - any help that anyone could offer would be great.
Upvotes: 0
Views: 116
Reputation: 3831
Let's assume you have a route like this:
get '/glossary/:id', :as => :glossary
Now, in your index page you're going to have code that looks something like:
<% ('a'..'z').to_a.each do |f| %->
<%= link_to "#{f}", "/glossary/#{f}" %>
<% end %>
or
<% ('a'..'z').to_a.each do |f| %->
<%= link_to "#{f}", glossary_path(:id => f) %>
<% end %>
The second is preferable. Read more here. Keep in mind that you can experiment with your named routes in the rails console, like so:
$ rails console --sandbox
Loading development environment in sandbox (Rails 3.1.3)
Any modifications you make will be rolled back on exit
ruby-1.9.3-p0 :001 > app.glossary_path(:id => 'a')
=> "/glossary/a"
Upvotes: 1