Modifying a method and using params in Rails3
Recently I started using https://g开发者_Go百科ithub.com/crowdint/rails3-jquery-autocomplete
It works great, but I was trying to set a scope for the results that I was autocompleteing, in this question I got a good answer: Scoping the results for rails3 jquery autocomplete plugin
Using Claudio's code I've successfully scoped as such:
class PostsController < ApplicationController
autocomplete :post, :title
def get_items(parameters)
Post.where(:user_id => current_user.id)
end
This works because I'm overwriting the plugin's get_items method. Which you can see here: https://github.com/crowdint/rails3-jquery-autocomplete/commit/b3c18ac92ced2932ac6e9d17237343b512d2144d#L1R84 (I have a version before this commit, so get_items still works for me).
The problem with my scope, is the autocomplete functionality no longer works. When the person starts typing, the list specified in get_items just pops up, rather than items being suggested from that list.
I'm assuming I'm doing something wrong with my overwriting method. Any ideas?
Best, Elliot
You just made me realize that overriding get_items is not as flexible as it should be.
Your code is missing the use of parameters[:terms]
Something like this should make it work:
def get_items(parameters)
Post.where(:user_id => current_user.id).where(['title LIKE ?', "#{parameters[:term]}%"]
end
This is totally unfriendly, I'll try and work on something that makes more sense
Or, maybe a :scope option for the autocomplete declaration makes more sense?
What if you have autocomplete for multiple fields though? For example, say you want to apply it to both title and author. How would you rewrite the following so it could serve both?
autocomplete :note, :title, :full => true autocomplete :note, :author, :full => true
def get_items(parameters) Note.select("distinct title").where(["title LIKE ?", "#{parameters[:term]}%"]) end
Currently that only works for the title field. It kills the autocomplete for the author field.
精彩评论