作者:最丑的美女mm_512 | 来源:互联网 | 2023-10-10 13:57
Inthepast,wheneverIwantedtoupdateapartofmyviewthroughAjax,Ivedonethefollowing:过去
In the past, whenever I wanted to update a part of my view through Ajax, I've done the following:
过去,每当我想通过Ajax更新我的部分视图时,我都会做到以下几点:
- create a partial out of the part I want to update and give it a unique ID, say
#tracks
- 创建一个我想要更新的部分,并给它一个唯一的ID,比如#tracks
- create a special action in the controller for that Ajax call, say
remove_track
that updates all the values, etc. and add format.js
- 在控制器中为该Ajax调用创建一个特殊操作,比如说更新所有值的remove_track等,并添加format.js
- create a new JS file with the same name as the action so Rails calls it automatically
remove_track.js.erb
which contains something like: $('#tracks').html("<%=j render 'cds/show_tracks' %>");
- 创建一个与动作同名的新JS文件,以便Rails自动调用它remove_track.js.erb,其中包含:$('#trackss).html(“<%= j render'cds / show_tracks'%> “);
- set
remote: true
in the link that calls this action.
- 在调用此操作的链接中设置remote:true。
All this is fine, but now I am trying to delete and update a common index
view using the regular destroy
method for flexibility, meaning I can call this method either through Ajax or normally. I figured it's such a common thing to do that there has to be a better way than all of the above.
所有这一切都很好,但现在我尝试使用常规destroy方法删除和更新公共索引视图以获得灵活性,这意味着我可以通过Ajax或通常调用此方法。我认为这样做很常见,必须有比上述所有方法更好的方法。
I can get the destroy method to call my destroy.js.erb
file by simply putting this into the controller:
我可以通过简单地将它放入控制器来获取destroy方法来调用我的destroy.js.erb文件:
format.js { layout: false }
and of course setting remote: true
on the link.
当然在链接上设置remote:true。
what I cannot do is get the view to refresh. The table I want to refresh is encased in a div with a unique ID, but since it's not a partial, it refuses to refresh the content. Maybe I'm missing something.
我不能做的是让视图刷新。我要刷新的表包含在具有唯一ID的div中,但由于它不是部分ID,因此它拒绝刷新内容。也许我错过了一些东西。
Am I doomed to have to create a partial and refresh it with the method above or is there a more magical way of doing it (other than using Turbolinks)?
我注定要创建一个局部并使用上面的方法刷新它,还是有更神奇的方法(除了使用Turbolinks)?
Thanks.
谢谢。
PS Also, I just noticed this has the added disadvantage that I cannot pass the rest of the params to the destroy method since it only passes the object ID to destroy using the regular CRUD routes. If I try to use platform(action: destroy)
or platform(method: delete)
I get an error:
PS此外,我只是注意到这有一个额外的缺点,我不能将其余的参数传递给destroy方法,因为它只使用常规CRUD路径传递对象ID以进行销毁。如果我尝试使用platform(action:destroy)或platform(method:delete),我会收到一个错误:
No route matches {:action=>"destroy", :cOntroller=>"platforms"}
Which means I have to create a new route if I want to pass those parameters...
这意味着如果我想传递这些参数,我必须创建一个新路线...
Yet another disadvantage to all this is that I'm repeading all the logic for searches and sorting that I have in the index method again in the destroy method. I am certain this is definitely not the way to do it.
所有这一切的另一个缺点是,我在destroy方法中再次重复索引方法中的搜索和排序的所有逻辑。我确信这绝对不是这样做的方法。
1 个解决方案