用户帖子的rails ajax fav按钮

用户帖子的rails ajax fav按钮,第1张

用户帖子的rails ajax fav按钮

首先,您需要设置数据库来处理此问题,就我个人而言,我将使用has_many:through关联,因为它比has_and_belongs_to_many具有更大的灵活性。但是,选择取决于您。我建议您在API中查找不同的类型,然后自己决定。此示例将处理has_many:through。

楷模

# user.rb (model)has_many :favoriteshas_many :posts, :through => :favorites# post.rb (model)has_many :favoriteshas_many :users, :through => :favorites# favorite.rb (model)belongs_to :userbelongs_to :post

控制者

# favorites_controller.rbdef create  current_user.favorites.create(:post_id => params[:post_id])  render :layout => falseend

路线

match "favorites/:post_id" => "favorites#create", :as => :favorite

jQuery的

$(".favorite").click(function() {  var post_id = $(this).attr('id');  $.ajax({    type: "POST",    url: 'favorites/' + post_id,    success: function() {      // change image or something    }  })})

笔记

这假设了两件事:使用Rails 3,使用jQuery,每个喜欢的图标都有一个带有帖子ID的html
ID。请记住,我尚未测试代码,而是在此窗口中编写的,因此您可能必须修复一些小问题,但它应该使您对
通常的 *** 作方式有一个印象。视觉的东西,等等,我会留给你的。

如果有人发现任何错误,请随时编辑此帖子。



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5622788.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存