Rails 3:has_many:通过保存问题?

时间:2010-12-18 06:14:50

标签: ruby-on-rails ruby-on-rails-3 has-many-through

我希望有人可以向我解释为什么我无法保存新记录?

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时,方法记录永远不会保存?为什么呢?
已编辑:已添加我的控制器。我在show action上打电话给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 个答案:

答案 0 :(得分:1)

也许你想要:

belongs_to :post

而不是

belongs_to :posts