:collection 参数接受一个键/值对数组:
[ [key, value], [key, value], [key, value], ... ]
其中key是选项值,value是选项文本。
最好在与要为其生成选项列表的对象对应的模型中生成此数组,而不是在您的视图中。
听起来您已经启动并运行了 best_in_place,因此这里有一个项目显示页面的简单示例,您希望在其中使用 best_in_place 通过选择框更改特定项目的分配用户。
## CONTROLLER
# GET /projects/1
# GET /projects/1.xml
# GET /projects/1.json
def show
@project = Project.find(params[:id])
respond_to do |format|
format.html
format.xml { render :xml => @project.to_xml }
format.json { render :json => @project.as_json }
end
end
## MODELS
class User
has_many :projects
def self.list_user_options
User.select("id, name").map {|x| [x.id, x.name] }
end
end
class Project
belongs_to :user
end
## VIEW (e.g. show.html.erb)
## excerpt
<p>
<b>Assigned to:</b>
<%= best_in_place @project, :user_id, :type => :select, :collection => User::list_user_options %>
</p>
# note :user_id and not :user
请注意,无论值是否更改,best_in_place 的主版本都会发送 ajax 请求以获取选择框。
还有一点要记住; best_in_place 用于“就地”编辑现有记录,而不是创建新记录(为此,在新页面的 _form 部分中使用 collection_select)。