【问题标题】:ajax in ruby on rails for a like/unlike buttonruby on rails 中的 ajax 用于喜欢/不喜欢按钮
【发布时间】:2012-09-09 08:41:39
【问题描述】:

所以我在我的 cmets 下有一个带有类似按钮的页面,我正在尝试解决如何在不刷新整个页面的情况下执行此操作,目前代码如下所示:

- if can? :like, comment
  = " · "
  - if likes.find_by_user_id(current_user.id).nil?
    = link_to "Like", like_comment_path(comment), method: :post
  - else
    = link_to "Unlike", unlike_comment_path(comment), method: :post
- if comment.user == current_user
  = " · "
  = link_to "Delete", comment_path(comment), method: :delete,
    :data => { :confirm => "Are you sure you want to delete this comment?" }
- if likes.count > 0
.comment-likes
  - likers = likes.map { |like| link_to(like.user_name, "#") }
  - if likers.length > 1
    - likers = likers.slice(0, likers.length - 1).join(", ").concat(" and " +                               likers.slice(-1))
  - else
    - likers = likers[0]
  = "Liked by #{likers}".html_safe

将喜欢和不喜欢的方法 :post 更改为 :update 似乎有很大的不同,这个函数使用 ajax 和 :post 不是吗?如果不是,那么我将如何将它变成一个 ajax 函数。

这是我的 cmets_controller.rb 的东西

def like
 comment_vote = resource.like current_user
 Event.comment_liked!(comment_vote)
 redirect_to discussion_url(resource.discussion)
end

def unlike
 resource.unlike current_user
 redirect_to discussion_url(resource.discussion)
end

【问题讨论】:

    标签: ruby-on-rails ajax coffeescript haml


    【解决方案1】:

    = link_to "Like", like_comment_path(comment), method: :post, remote: true

    然后在你的 likes_controller 创建动作,respond_to format.js

    def create
      respond_to do |format|
        format.html { .. your liking code .. }
        format.js {.. your liking code .. }
      end
    end
    

    这将调用您视图文件夹中的 create.js.erb,您可以从那里动态更新您的 html

    【讨论】:

    • 谢谢今晚试试这个。
    • 我无法让这项工作正常工作,如果您能给我一些指导来使用我喜欢和不同的功能,我已经在上面的问题中包含了我的 cmets_controller.rb 文件,这将是很棒的@Amir
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-20
    • 2014-09-21
    • 2016-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-22
    相关资源
    最近更新 更多