Rails 5.0 - 如何在不使用 gem 的情况下实现就地编辑best_in_place



我正在使用RoR构建一个事件站点,我刚刚升级到v5.0.1(尚未移至5.1)。我的事件显示页面在页面底部有一个评论部分,到目前为止,它只有创建和删除功能。 我想在评论中添加编辑/更新功能,以便只有创建评论的用户才能在他们认为合适的情况下编辑评论。我希望他们能够在同一页面上编辑他们的评论。

我正在尝试使用 remote:true 和 Ajax 来实现这些更改,而不是依赖 gem,因为它看起来不太复杂,但我以前从未这样做过,而且似乎没有通过互联网/SO 的明确指南。这是我的观点和控制器代码 -

comments_controller.rb

def create
@event = Event.find(params[:event_id])
@comment = @event.comments.create!(params[:comment].permit(:name, :body))
@comment.user_id = current_user.id

redirect_to @event
end
def update
@comment.user = current_user
respond_to do |format|
if @comment.update
format.html { redirect_to @comment, notice: 'Comment was successfully updated.' }
format.js   { }
format.json { render :show, status: :created, location: @comment }
else
format.html { render :new }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end

def destroy
@event = Event.find(params[:event_id])
@comment = @event.comments.find(params[:id])
@comment.destroy
redirect_to event_path(@event)
end

_comments.html.erb

<% if user_signed_in?  %>
<p><%= link_to "Edit", remote: true %></p>
<p><%= link_to 'Delete', [comment.event, comment],
method: :delete,
class: "button",
data: { confirm: 'Are you sure?' } %></p>
<% end %>

我的理解是,我需要在我的视图/评论文件夹中包含一个 .js.erb 文件来处理这个问题( edit.js.erb ?),但我不清楚的是我需要包含哪些 javascript 代码才能工作。另外,我认为上面的控制器代码似乎不正确 - 这应该进入编辑操作吗?我是否还需要事件控制器中的 Event#show 操作,因为这是它在视图中的位置?

任何协助将不胜感激。

我知道这并不能回答你的问题,但希望它能为你解决重新发明轮子方面的头痛问题。这也是为什么(我相信)你会看到反对票。

我不想使用best_in_place gem,因为它似乎有一段时间没有更新了,而且我不确定它是否最适合 Rails 5.0。

宝石不需要有活动才能仍然有用。"一段时间"的意思一定是"不到 24 小时前",因为我看到上个月有很多活动。一旦宝石解决了它通常就可以了。

https://github.com/bernat/best_in_place/commits/master

Rails 5 仍然处理 POST 请求,对吗?那么它应该可以工作。best_in_place比任何东西都更重 JavaScript。https://github.com/bernat/best_in_place/tree/master/lib/best_in_place

其中最"令人生畏"的代码是helper.rb文件,它呈现了与JS库挂钩的HTML。

更新:

注释/编辑.js.erb 文件将负责插入表单以编辑注释,例如$('div#new_comment').append('<%= j render 'form' %>');

这假设你在元素/ID命名方面使用了Rails的约定。

如果您有link_to("Edit", edit_comment_path(comment), :remote => true)则所有内容都应自动触发。

下面是一个使用 Rails 4 的示例存储库;对于 Rails 5 应该是一样的,除了(也许)respond_to块?我不确定,还没有使用过Rails 5。只需做一个bundlerake db:setup,然后做一个rails s;导航到"http://localhost:3000/events并享受"。

你使用edit.js.erb 走在正确的轨道上。该文件应包含用于设置编辑屏幕的JS代码,例如,可能会隐藏DIV,而是显示INPUT或TEXTAREA。

当然,该文件也可以包含 Ruby 代码,在 <% %> 标签内。

相关内容

最新更新