简体   繁体   English

Ruby on Rails-在显示布局中编辑/更新内容

[英]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: 我相信他们正在做的是:

  1. When you click the 'Edit' button, Javascript is generating/displaying a hidden layout with the text_area . 当您单击“编辑”按钮时,Javascript正在使用text_area生成/显示隐藏的布局。
  2. Clicking 'Save' will send a request off in the background, without refreshing the screen. 点击“保存”将在后台发送请求,而不刷新屏幕。
  3. Javascript will take the updated text and copy it into the old layout, and display that. Javascript将获取更新的文本并将其复制到旧的布局中,并进行显示。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM