开发者

Rails 3: mysql query adjustment

I'm using jquery_token_input after following Ryan Bates railscast #258 and this is the code in the authors controller that searchs the entered query and produces json to render the autocomplete list. Currently it selects the authors where the name is like the params entered.

Authors controller

def index
  @authors = Author.where("name like ?", "%#{params[:q]}%")
  respond_to do |format|
    format.html
    format.json { render :json => @authors.map(&:attributes) }
  end
end

The author model has the columns :name and :user_id. I'd like to first select authors where the user_开发者_如何转开发id is equal to the current_user.id. And then to select from that array the authors whos name is like the params entered.

Does this make sense? Any insight is greatly appreciated.


This ended up being the line I needed: (I have a helper method called uid)

def index
 @authors = Author.where(:user_id => uid).where(["name like ?", "%#{params[:q]}%"])
  respond_to do |format|
    format.html
    format.json { render :json => @authors.map(&:attributes) }
  end
end

Is there a way to improve this by removing the second where? Does that even matter?


I'd like to first select authors where the user_id is equal to the current_user.id.

Sounds strange. Assuming user_id is the primary key this should return exactly one result (or none); but never a list of authors.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜