2012-09-07 50 views
2

我正在開發一個用戶可以發佈的Rails應用,必須像Facebook一樣。我想實現一個通知系統,提醒用戶注意新帖子。但是,如何判斷用戶是否查看了帖子,我遇到了問題。我從字面上無能爲力。Rails新郵件通知

我使用設計的寶石,給了我獲得一定的用戶統計數據(如果這能幫助):

create_table "users", :force => true do |t| 
    t.string "email",     :default => "", :null => false 
    t.string "encrypted_password",  :default => "", :null => false 
    t.string "reset_password_token" 
    t.datetime "reset_password_sent_at" 
    t.datetime "remember_created_at" 
    t.integer "sign_in_count",   :default => 0 
    t.datetime "current_sign_in_at" 
    t.datetime "last_sign_in_at" 
    t.string "current_sign_in_ip" 
    t.string "last_sign_in_ip" 
    t.string "confirmation_token" 
    t.datetime "confirmed_at" 
    t.datetime "confirmation_sent_at" 
    t.string "unconfirmed_email" 
    t.integer "failed_attempts",  :default => 0 
    t.string "unlock_token" 
    t.datetime "locked_at" 
    t.string "authentication_token" 
    t.datetime "created_at",        :null => false 
    t.datetime "updated_at",        :null => false 
    t.string "username",    :default => "", :null => false 
    t.integer "admin",     :default => 0 
    end 

而且我樁模型:

create_table "posts", :force => true do |t| 
    t.integer "user_id" 
    t.text  "content" 
    t.datetime "created_at",    :null => false 
    t.datetime "updated_at",    :null => false 
    end 

我如何能實現一個知道一個系統如果用戶看過帖子或沒有?

回答

3

簡單的形式給出了會是這樣的:

創建一個名爲模型中看到

rails g model Seen post:references user:references 

型號/ seen.rb

belongs_to :user 
belongs_to :post 

型號/ user.rb

has_many :seens 
has_many :seen_posts, through: :seens, source: :post 

型號/ post.rb

has_many :seens 
has_many :seen_users, through: :seens, source: :user 

,你可以創建一個方法類似的東西

型號/ post.rb

def seen_by?(user) 
    seen_user_ids.include?(user.id) 
end 

控制器/ posts_controller.rb

def show 
    @post = Post.find(params[:id]) 
    current_user.seen_posts << @post unless @post.seen_by?(current_user) 
end 
+0

如果我每分鐘都進行一次這樣的調查,那會得到相當密集的數據庫嗎?我從來沒有這樣做過,所以我真的不知道。但是,我想實際上沒有其他方式來跟蹤用戶查看的帖子。 – flyingarmadillo