【问题标题】:rails 4, ajax changing methods in formrails 4,表单中的ajax更改方法
【发布时间】:2016-01-27 22:49:56
【问题描述】:

我可以在第一次点击时点赞并更新点赞数,但在第二次点击时就不行了。我在帖子需要更改的地方对其进行了调试,但我无法弄清楚如何更改 ajax 调用中的表单方法。

skit_controller.rb

def like
  @skit.liked_by current_user   if request.post?
  @skit.unliked_by current_user if request.delete?
  respond_to do |format|
    format.html { redirect_to skits_path, notice: 'Successfully voted!' }
    format.js
  end
end

routes.rb

resources :skits do
  resources :challenges
  match :like, via: [:post, :delete], on: :member
end

index.html.haml

- @skits.each do |skit|
  = render skit

_skit.html.haml

.votes
  - method = current_user.liked?(skit) ? :delete : :post
  = link_to like_skit_path(skit), method: method, remote: true, id: "post-#{skit.id}" do
    .upvote
      %span.upvote-link
        %i.fa.fa-caret-up
      .vote-count= skit.votes_for.size

like.js.erb

$("#post-<%= @skit.id %>").find(".vote-count").html('<%=j @skit.votes_for.size.to_s %>');

我认为每次有人单击按钮时我都需要更新方法,因此用户可以:post 点赞或:delete 点赞,但它只是停留在 POST 方法。

【问题讨论】:

  • 所以delete 不起作用?
  • @Marwen 点击后不会切换方法。
  • 让我写下答案。

标签: jquery ruby-on-rails ajax ruby-on-rails-4


【解决方案1】:

我们将不得不更新您的布局。

skits/_skit.html.haml

.skit-wrapper{id: "skit-#{skit.id}"}
  =render partial: 'skits/skit_wrapper', locals: {skit: skit}

skits/_skit_wrapper.html.haml

.votes
  - method = current_user.liked?(skit) ? :delete : :post
  = link_to like_skit_path(skit), method: method, remote: true do
    .upvote
      %span.upvote-link
        %i.fa.fa-caret-up
      .vote-count= skit.votes_for.size

like.js.erb

$("#skit-<%= @skit.id %>").html("<%= escape_javascript(render partial: 'skits/skit_wrapper', locals: {skit: @skit}) %>")

【讨论】:

  • 很高兴听到这个消息!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-29
  • 1970-01-01
  • 1970-01-01
  • 2015-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多