【发布时间】:2017-06-25 07:28:54
【问题描述】:
我有一张带有共享类别参数的图片。现在,当我在模式中创建或编辑该图像时,它的功能正是我想要的。它使用几个 js.erb partials 来调用 new、create、edit 和 update。
我还希望能够通过单击复选框来更新图像显示页面上的类别,并使用 ajax 立即进行更新,而无需按下按钮。
其中大部分也适用于我。如果我单击复选框并按下按钮进行更新,则通过控制器中的更新操作。我的 CoffeeScript 是这样写的,如果在其中一个框中打勾并且我将它设置为 console.log 或 alert("whatever") 它会。我需要做的是弄清楚如何连接这两者,而不使用我之前使用的update.js.erb 和edit.js.erb,因为它们一个触发打开模式,另一个触发关闭它。在这种情况下,这些都不是必需的。
我无法理解的是,因为我已经在使用更新和编辑操作,我如何调用它们来做新的事情,更新渲染任何东西?
我认为可以在路由中创建额外的图像路径并在控制器中创建新操作。由于我不确定这是否是正确的方法,所以我尝试在网上查找可能涵盖该主题的教程或博客文章,但我还没有找到任何地方。
有谁知道如何做我想要弄清楚的事情? 在此先感谢您的帮助
编辑添加的代码和更好的描述尝试:
这是我在 index.js 中开始的更新操作的代码。一个链接用来调用edit.js.erb,它调用edit.html.erb,它会渲染一个部分的表单。点击提交后更新。 update.js.erb 被称为关闭模态,保存更新并在原始索引页面上渲染更新。我喜欢它,它按我的意愿工作:
图像控制器
...
def show
@image = Image.find(params[:id])
@categories = current_user.categories.all
end
def update
@image.update(image_params)
redirect_to user_images_url(current_user), notice: 'Image Updated'
end
private
def image_params
params.require(:image).permit(:file, :start_at, :end_at, category_ids: [])
end
edit.js.erb
$("#image-modal").html("<%= j render 'edit' %>")
$("#image-modal").modal("show")
edit.html.erb
<%= render 'form' %>
图像/_form.html.erb
<%= simple_form_for shallow_args(current_user, @image) do |f| %>
<%= f.label :category_ids, "Categories" %><br>
<%= f.collection_select :category_ids, current_user.categories.all, :id, :name, {}, { multiple: true } %>
<%= f.file_field :file, class: "fileinput-new" %>
<%= f.button :submit, "Add" %><br>
<%= link_to "Cancel", "#", class: "btn", data: {dismiss: "modal"} %>
update.js.erb
$("#images_<%= @image.id %>").replaceWith("<%= j render @image %>").preventDefault()
$("#image-modal").modal("hide")
这是让我感到困惑的代码。在@image 显示页面上,它们是与图像的用户/所有者关联的类别以及用户创建的所有类别的集合,无论它们当前是否与此图像相关联。与此图像关联的类别在其复选框中具有复选标记,其他类别则没有。如果我选中另一个复选框并按下提交,它会像没有关联 ajax 的普通表单一样更新,重新加载整个页面。我想让它当我选中一个未选中的框或取消选中一个选中的框时,它会立即更新数据库,而无需按下更新按钮。我已经使用 update.js.erb 和 edit.js.erb 从索引页面更新我的图像,所以我不能使用它们从显示页面更新我的图像(tutorials tell me to use them)。用于更新的显示页面的 jquery 行为与用于从索引页面更新的 jquery 非常不同。
关于我的咖啡脚本的一点是为了证明 .click 脚本有效,所以我的问题不在于那部分。
我希望这更清楚。
图像/show.html.erb
<div class="image-show">
<%= image_tag(@image.file_url(:show).to_s) %>
</div>
<div id="category-list">
<%= simple_form_for shallow_args(current_user, @image), remote: true do |f| %>
<%= f.collection_check_boxes :category_ids, current_user.categories.all, :id, :name, {}, { multiple: true } %>
<%= f.button :submit, "Add" %><br>
<% end %>
</div>
images.coffee
$ ->
$('.edit_image input[type=submit]').remove()
$('.edit_image input[type=checkbox]').click ->
$(this).parent('form').submit()
return
【问题讨论】:
-
您需要在问题中添加代码。否则我们只是猜测。如果你真的必须使用 rails 模板系统,我的 2c 只使用
js.erb。如果您将一堆客户端逻辑填充到js.erb模板中,您会得到这个易碎的汤,rails 突然负责维护客户端的状态。这是完全错误的。 -
你的问题真的很难阅读和理解。请尽量让它更清楚。
-
谢谢,我刚刚添加了代码并试图更好地解释它。
标签: javascript jquery ruby-on-rails ajax coffeescript