2011-08-01 77 views
7

我在用戶帖子(顯然是嵌套資源)上查詢過,並且有來自不同用戶的帖子很長的列表。我希望用戶能夠點擊每個帖子旁邊的小星星,通過ajax來收藏該特定帖子。有關如何實現這一目標的任何建議?我遇到的麻煩是在一個頁面上多個最喜愛的按鈕,偏愛多個帖子。用戶帖子的rails ajax fav按鈕

這就像Gmail在收件箱中收藏的電子郵件一樣。其實,就是這樣。

回答

10

首先你需要設置數據庫來處理這個問題,我個人會使用has_many:through關聯,因爲它提供了比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,每個收藏圖標與的帖子ID的HTML標識。請記住,我沒有測試代碼,並且我在此窗口中編寫了代碼,因此您可能必須修復一些小問題,但它應該給你一個如何通常這樣做的印象。視覺材料和我會留給你的。

如果有人發現任何錯誤,請隨時編輯這篇文章。

1

對爲每個喜歡的按鈕做form_tag。將帖子和當前登錄用戶的ID添加爲每個表單的隱藏字段。

爲了更新收藏夾狀態,您可以編寫一個RJS視圖,該視圖將包含jQuery以將收藏夾更新爲「張貼已被收藏」。

事情是這樣的:

- 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" 

您可以自定義提交按鈕(S)的外觀是用CSS明星的形象。

如果你想提供一個選項來選擇多個帖子,然後一次最喜歡它們,你將不得不編寫自定義的javascript來處理它。在「收藏所有選定」按鈕的點擊處理程序上,然後在該處理程序中收集所有已選定的帖子ID,將ID序列化爲字符串並將其發回給控制器。