我正在使用 RoR 构建一个事件站点,我刚刚升级到 v5.0.1(尚未升级到 5.1)。我的事件显示页面在页面底部有一个评论部分,到目前为止,该部分仅具有创建和删除功能。 我想向评论添加编辑/更新功能,以便只有创建评论的用户可以编辑评论(如果他们认为合适)。我希望他们能够在同一页面上编辑评论。
我正在尝试使用remote: true 和 Ajax 来实现这些更改,而不是依赖 gem,因为它看起来不太复杂,但我以前从未这样做过,而且似乎没有通过互联网/SO 提供清晰的指南。这是我的 View 和 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 %>
我的理解是,我需要在 View /评论文件夹中包含一个 .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 不需要有事件就仍然有用。您所说的“一段时间”一定是指“不到 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' %>');
这假设您使用 Rails 的元素/ID 命名约定。
如果您有 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/