How do I set my rails app up so that I can click a letter and see only the entries starting with that letter?

StackOverflow https://stackoverflow.com/questions/19687086

سؤال

My rails app basically displays a dictionary of sorts, which is stored in a database. I've set up a basic rails app with scaffold to display this on a webpage, but I can't for the life of me figure out how to set this next bit up. Basically I want a row of the 26 alphabetical letters, and when you click on a letter (say 'A'), I only want to see the dictionary entries of that letter.

My index.html.erb file:

<% for char in 'A'..'Z' %>
<%= link_to( "#{char}", "/words/lettersearch", :id => "#{char}") %>
<% end %>

my words_controller.rb file method for doing this:

def lettersearch
    @word = Word.find(:all, :conditions => ["word LIKE ?", "#{params[:word]}%"])
end

It then outputs the @word to another page.

My problem is that it just outputs the entire dictionary again, no matter what letter I click on the index page. I know it's to do with the routing, as it never seems to actually run the 'lettersearch' method - it's always trying to run through the 'Show' method that's defined by default earlier in the controller.

Anyone able to give me a quick hand with how to route this thing through? I'm pretty new to rails and I don't understand the workings of link_to very well at all.

routes.rb:

Dictionary::Application.routes.draw do
  resources :words do

  post 'search', :on => :collection
  post 'lettersearch', :on => :collection
  end

#Rest of routes.rb still commented apart from
   match ':controller(/:action(/:id))(.:format)'
هل كانت مفيدة؟

المحلول

You are passing in a param called :id but in your controller you use a param called :word

Also, update your code to use newer syntax

World.where(["word like ?", "#{params[:id]}%"])

And your view code can be cleaned as well

<% for char in 'A'..'Z' %>
  <%= link_to char, "/words/lettersearch", :id => char %>
<% end %>

Your routes file only has a POST route to letter search, but a link_to is a GET request. So whats happening is the GET request is hitting /words/:id via GET which is the show action by default, and the params[:id] inside that request will be "lettersearch"

نصائح أخرى

You could run the search in your index. I think that might be what you want to do. In your index controller you could put:

@orders = Order.lettersearch(params[:word])

and then in your model:

def lettersearch(word)

    if lettersearch
       @word = Word.find(:all, :conditions => ["word LIKE ?", "#{word}%"])
    else
       all
    end
end
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top