轨道AJAX收藏的按钮用户帖子 [英] rails ajax fav button for user posts

查看:96
本文介绍了轨道AJAX收藏的按钮用户帖子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经询问用户的帖子(嵌套的资源,很明显),并有来自不同用户的帖子很长的名单。我希望用户能够点击一个小星星旁边的每个岗位最喜欢的特定岗位,通过AJAX。任何建议如何实现这一目标?我遇到的麻烦是多收藏夹按钮在一个页面上,收藏多个帖子。

I have queried on user posts (nested resources, obviously) and have a long list of posts from different users. I would like the user to be able to click a little star next to each post to favorite that particular post through ajax. Any suggestions on how to achieve this? The trouble I'm running into is multiple favorite buttons on one page, favoriting multiple posts.

这是八九不离十像Gmail不会与喜爱的邮件在收件箱中。其实,这是完全一样的。

This is sorta like Gmail does with favorite emails in their inbox. Actually, it's exactly like that.

推荐答案

首先,您需要设置数据库处理这个问题,我个人会去用的has_many:通过关联,因为它提供了has_and_belongs_to_many更大的灵活性。选择却是由你。我建议你​​看看不同类型的API中,并自行决定。这个例子将处理的has_many:通过

First you need to set up the database to handle this, personally I'd go with a has_many :through association because it provides more flexibility over has_and_belongs_to_many. The choice, however, is up to you. I recommend you look up the different types in the API and decide for yourself. This example will deal with has_many :through.

模型

# user.rb (model)
has_many :favorites
has_many :posts, :through => :favorites

# post.rb (model)
has_many :favorites
has_many :users, :through => :favorites

# favorite.rb (model)
belongs_to :user
belongs_to :post

控制器

# favorites_controller.rb
def create
  current_user.favorites.create(:post_id => params[:post_id])
  render :layout => false
end

路线

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,每一个喜欢的图标都有一个HTML ID的文章ID。请记住,我没有测试code和我在这个窗口中写的,所以你可能要解决一些小问题,但它应该给你怎样的 <我的IM pression /强>通常不会这样。视觉的东西,这样我将离开你来决定。

This assumes a couple of things: Using Rails 3, using jQuery, each favorite icon has an html id with the post id. Keep in mind I've not tested the code and I wrote it in this window so you probably have to fix some minor problems, but it should give you an impression of how I usually does this. The visual stuff and such I'll leave up to you.

如果任何人发现任何错误,请随时编辑这篇文章。

If anyone spot any mistakes please feel free to edit this post.

这篇关于轨道AJAX收藏的按钮用户帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆