Rails 3 - best_in_place编辑
问题描述:
希望得到一个简单的答案;我正在使用gem best_in_place,它的效果很好。我试图找出如何使用创建一个下拉菜单:Rails 3 - best_in_place编辑
:type => :select, :collection => []
我希望能够做的就是通过在已经从我的用户模型中输入名称的列表。
任何想法如何做到这一点?我可以将它与collection_select混合使用吗?
答
的:采集参数接受键/值对的数组:
[ [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)。
谢谢!得到这个工作...很容易错过你的例子结尾处的代码,这要归功于OS X中的铬滚动。 – 2012-04-04 20:08:33
也许你应该选择这个作为你的答案,如果它对你有帮助。 – marcamillion 2012-11-30 16:59:14
感谢这个答案,一个问题是......我们如何让'select'中的'空白'选项被选中?即完全“空白”或“无”或类似的东西。 – marcamillion 2012-11-30 17:22:56