Rails 3-best_in_place编辑 [英] Rails 3 - best_in_place editing
问题描述
希望有一个简单的答案;我正在使用宝石 best_in_place ,它的效果很好.我试图弄清楚如何使用以下方法创建下拉菜单:
Hopefully a simple answer; I am using the gem best_in_place and it works great. I'm trying to figure out how to create a drop down menu using:
:type => :select, :collection => []
我想做的是传递从用户模型输入的名称列表.
What I want to be able to do is pass in a list of names that have been entered from my user model.
有没有想到该怎么做?我可以将其与collection_select混合吗?
Any thoughts how to do this? Can I mix it with collection_select?
推荐答案
:collection参数接受键/值对的数组:
The :collection parameter accepts an array of key/value pairs:
[ [key, value], [key, value], [key, value], ... ]
其中键是选项值,而 value 是选项文本.
最好在模型中生成该数组,该模型与要为其生成选项列表的对象相对应,而不是在视图中.
It is best to generate this array in the model corresponding to the object for which you want to generate a list of options for, and not in your view.
听起来像是best_in_place处于运行状态,所以这是一个项目显示页面的简单示例,您想在其中使用best_in_place来通过选择框更改特定项目的分配用户.
Sounds like you have best_in_place up and running, so here's a simple example of a project show page, where you want to use best_in_place to change the assigned user for a particular project with a select box.
## 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请求,以选择框是否值是否更改.
Note that from memory, the master version of best_in_place sends the ajax request for a select box whether the value is changed or not.
还有一些需要牢记的地方; best_in_place用于修改"现有记录,而不是创建新记录(为此,请在新页面的_form部分中使用collection_select).
Also something to keep in mind; best_in_place is for "in place" editing of existing records, not creating new ones (for that, use collection_select in your _form partial for the new page).
这篇关于Rails 3-best_in_place编辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!