[英]How to update/pre-populate Rails form using a dropdown
I am trying to create a form with dropdown where users can create a new object if something like "Create new" is selected, or they have the option of choosing from their previously created objects, which should prefill the form with the corresponding data. 我正在尝试使用下拉列表创建一个表单,如果选择了“创建新的”之类的东西,或者用户可以从先前创建的对象中选择,则用户可以创建一个新对象,这将用相应的数据预填充表单。
At the moment I simply have a for each loop filling the dropdown list with the previously created objects which is outside the form, and a form that creates new objects. 目前,对于每个循环,我只是有一个用于在下拉列表中填充表单外部的先前创建的对象以及创建新对象的表单。
How can I make this form dynamic so that when a previously selected object is selected, the form pre-fills and allows for editing? 如何使此表单具有动态性,以便在选择先前选择的对象时,该表单会预先填充并允许编辑?
You'd have to send out an AJAX GET request to a custom route and then have a controller action that responds to json
format and returns a collection based on params passed in that GET request. 您必须将AJAX GET请求发送到自定义路由,然后执行控制器操作以响应
json
格式,并根据在该GET请求中传递的参数返回集合。 Say, you are loading available car models based on a selected make: 假设您要根据选定的品牌加载可用的汽车型号:
routes: 路线:
get '/get_models/:make_id', to: 'car_makes#available_models'
controller action: 控制器动作:
def available_models
@models = Model.where(id: ids)
respond_to do |format|
format.json { render json: @models }
end
end
AJAX request: AJAX请求:
var fetchModels = function(makeId){
$.ajax({
method: 'GET',
url: '/get_models/' + makeId,
success: function(data) {
...
var target = $('select#car_models'); // field to which options are appended
$.each(data, function(id, model){
$(target).append(
$('<option>').text(model).attr('value', id) // populate options );
});
}
...
});
}
and then setting the AJAX request to fire on .change
event in a parent select
field: 然后在父
select
字段中将AJAX请求设置为在.change
事件上.change
:
$('select#car_makes').change(function(){
var makeId = $(this).val();
fetchModels(makeId);
});
There are a number of resources explaining other ways to achieve this: 有许多资源说明了实现此目标的其他方法:
So I ended up looping through all of the potential options for the select dropdown, and looping through the edit rails form with all the potential options, and using jQuery onchange to show / hide the correct html. 因此,我最终遍历了select下拉列表的所有可能选项,并遍历了带有所有潜在选项的edit rails表单,并使用jQuery onchange显示/隐藏了正确的html。
This doesn't feel like a very good solution to me, especially as it has to load the html of all the options every time.. but I don't know what else to do and it works. 这对我来说不是一个很好的解决方案,尤其是因为它每次都必须加载所有选项的html ..但我不知道该怎么办才能奏效。
If anyone has any ideas for a better solution, let me know :) 如果有人对更好的解决方案有任何想法,请告诉我:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.