rails ajax fav按钮用于用户post

我查询了用户post(显然是嵌套资源),并且有很多来自不同用户的post。 我希望用户能够点击每个post旁边的一个小星星,通过ajaxcollections该特定post。 有关如何实现这一目标的任何建议? 我遇到的麻烦是一个页面上有多个喜欢的按钮,喜欢多个post。

这有点像Gmail在收件箱中collections了最喜欢的电子邮件。 实际上,它就是这样的。

首先,您需要设置数据库来处理这个问题,我个人会选择has_many:通过关联,因为它提供了比has_and_belongs_to_many更多的灵活性。 然而,选择权取决于您。 我建议您查找API中的不同类型并自行决定。 这个例子将处理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,每个collections夹图标都有一个带有postID的html id。 请记住,我没有测试过代码,我在这个窗口中编写了代码,所以你可能需要解决一些小问题,但它应该给你一个通常如何做的印象。 视觉的东西,我会留给你。

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

为每个collections夹按钮执行form_tag :remote => true 。 将post的ID和当前登录的用户添加为每个表单的隐藏字段。

要更新collections状态,您可以编写一个RJS视图,其中包含jQuery以将collections更新为“post is favited”。

像这样的东西:

  - for post in @posts = form_tag toggle_favorite_post_path, :remote => true = hidden_field_tag :post_id, post.id = hidden_field_tag :user_id, current_user.id - if Favorite.where(:post_id => post.id, :user_id => current_user.id).exists? # TODO: move this to model = submit_tag "Add to favorites", :class => "favorite-post-button" - else = submit_tag "Remove from favorites", :class => "unfavorite-post-button" 

您可以使用CSS将提交按钮的外观自定义为星形图像。

如果你想提供一个选项来选择多个post然后一次collections它们,你将不得不编写自定义的javascript来处理它。 在“最喜欢的所有选定”按钮的单击处理程序上,然后在该处理程序内,收集所有已选择的postID,将ID序列化为字符串并将其发送回控制器。