Rails auto_complete与对象的子集

时间:2010-11-30 16:20:37

标签: ruby-on-rails autocomplete ruby-on-rails-plugins

以下是我的模特:

class User < ActiveRecord::Base
  has_many    :artists
end

class Artist < ActiveRecord::Base
  belongs_to    :user
end

我正在尝试实现自动完成艺术家姓名的auto_complete文本字段:

<%= text_field_with_auto_complete :artist, :name, { :size => 60}, {:skip_style => false, :tokens => ','} %>

这可以工作,但会自动填充数据库中定义的所有艺术家。我需要做什么才能将返回的auto_complete结果限制为仅属于登录用户的艺术家?

非常感谢!

1 个答案:

答案 0 :(得分:2)

据推测,你的控制器里有这样的东西:

def auto_complete_for_artist_name
  @artists = Artist.find(:all, 
   :conditions => "name LIKE (?)", params[:artist][:name])
end

您需要将其更改为将当前用户添加到条件中或使用如下关联:

def auto_complete_for_artist_name
  # assumes you have a 'current_user' method 
  # which returns the current logged in user
  @artists = current_user.artists.find(:all, 
     :conditions => "name LIKE (?)", params[:artist][:name])
end

这将为您提供属于当前用户的艺术家。