[英]Ruby on Rails - Edit/Update Content on Show layout
I'm trying to find out how to implement a system that allows me to update certain fields without navigating away from the current page, and without reloading it. 我正在尝试找出如何实现一个系统,该系统允许我更新某些字段而无需离开当前页面,也无需重新加载它。
I've seen this on a lot of websites, including editing comments on StackOverflow. 我已经在很多网站上看到了这一点,包括在StackOverflow上编辑评论。
Example: 例:
You wrote and posted a Comment
. 您撰写并发表了
Comment
。 While looking at all the posted Comments
, there is a 'Edit' button that changes that Comment
back into a text_area
in place, allowing you to update the text, and a button to save it. 在查看所有已发布的
Comments
,有一个“编辑”按钮,可将该Comment
回到适当的text_area
位置,允许您更新文本,还有一个按钮用于保存文本。 Then the updated Comment
looks correct, and you didn't need to navigate or refresh. 然后,更新后的
Comment
看起来正确,您无需导航或刷新。
I believe what they're doing is: 我相信他们正在做的是:
text_area
. text_area
生成/显示隐藏的布局。 Is there any good examples of how to implement this? 有没有很好的例子来实现这一目标? I'm not even sure what terminology is used for this kind of updating.
我什至不确定这种更新使用了什么术语。
Thanks for your help. 谢谢你的帮助。
There exist many examples to reach your goal. 有许多示例可以实现您的目标。
Give me a try to give you a simple example for a better understanding. 请尝试给我一个简单的例子,以使您更好地理解。
Let's say you have a Post
model 假设您有一个
Post
模型
class Post
end
Your index page like the following (in controller index @posts = Post.all
您的索引页面如下所示(在控制器索引
@posts = Post.all
<% #app/views/posts/index.html.erb %>
<div id="posts">
<%= render @posts %>
</div>
The post object partial: post对象的局部:
<% #app/views/posts/_post.html.erb %>
<div id="<%= dom_id(post)%>">
<%= post.title %>
</div>
And update your form_for
tags with the remote attribute 并使用remote属性更新
form_for
标签
form_for @post, remote: true
Now your create could add the current post to the div#posts or replace the entire div. 现在,您的创建可以将当前帖子添加到div#posts或替换整个div。
<% #app/views/posts/create.js.erb %>
$("#posts").append('<%=j(render @post)%>')
Your update could update one entry by replacing the div with the dom_id()
for the updated post. 您的更新可以通过将div替换为更新后的帖子的
dom_id()
来更新一项。
<% #app/views/posts/update.js.erb %>
$("#posts ##{dom_id(@post)}").html('<%=j(render @post)%>')
That's all. 就这样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.