gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 17:44:17 25 4
gpt4 key购买 nike

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

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

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 %>

我的理解是我需要在我的 views/comments 文件夹中包含一个 .js.erb 文件来处理这个( edit.js.erb ?)但我不清楚的是我需要什么 javascript 代码包括为了使这个工作。此外,我认为我上面的 Controller 代码似乎不正确 - 这应该在编辑操作中进行吗?我是否还需要在我的事件 Controller 中执行 Event#show 操作,因为它位于 View 中?

如有任何帮助,我们将不胜感激。

最佳答案

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

I don't want to use best_in_place gem as it appears to not have been updated for a while and I'm not sure if its the best fit for Rails 5.0.

gem 不需要有 active 也能发挥作用。 “一段时间”,你的意思一定是“不到 24 小时前”,因为我在上个月看到了很多事件。一旦 Gem 解决了它通常就可以了。

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 文件,它呈现 Hook 到 JS 库中的 HTML。

更新:

comments/edit.js.erb 文件负责插入表单来编辑评论,例如$('div#new_comment').append('<%= j render 'form' %>');

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

如果你有一个 link_to("Edit", edit_comment_path(comment), :remote => true)一切都应该自动触发。

Here's an example repo using Rails 4 ;对于 Rails 5 应该是相同的,除了(可能)respond_to block ?我不确定,还没有使用过 Rails 5。只需做一个 bundle , rake db:setup , 然后是 rails s ;导航至 http://localhost:3000/events并享受。

关于ruby-on-rails - Rails 5.0 - 如何在不使用 best_in_place gem 的情况下实现就地编辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44027374/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com