2010-12-18 4 views
2

誰かが私に新しい記録を保存できない理由を説明できると思っていましたか?Rails 3:has_many:throughtの問題を保存しますか?

class User < ActiveRecord::Base 

    has_many :viewed_posts, :dependent => :destroy 
    has_many :posts, :through => :viewed_posts 

    def update_viewed_posts(post) 
     if viewed_posts.where("id IN(?)", post.id).blank? 
      puts '----------------------- NEVER READED POST' 
      viewed_posts.build(:question_id => post.id, :user_id=> self.id) 
     end 
    end 
end 

class ViewedPosts < ActiveRecord::Base 
    belongs_to :post 
    belongs_to :user 
end 

私はupdate_view_posts方法レコードが保存されることはありません呼び出すときに私の質問はありますか?どうして?
EDITED:マイコンが追加されました。私はショーアクションでupdate_view_postsと呼んでいます。

class PostsController < ApplicationController 
    respond_to :html 

    before_filter :find_post, :only => [:show, :edit, :update, :destroy] 

    def show 
     if current_user 
      current_user.update_viewed_posts(@post) 
     end 
    respond_with(@post) 
    end 
end 

答えて

1

たぶんあなたが欲しい:

belongs_to :post 

代わりの

belongs_to :posts 
+0

私はミスを犯します。それはポストではない。それはポストです。 – Zeck

+0

ユーザIDを自動的に知る必要があるので、 "viewed_posts.build(:question_id => post.id)"に変更してみてください。 –

+0

Doh、働かないでください。何か案が? – Zeck