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

发布于 2024-10-07 21:46:18 字数 980 浏览 7 评论 0原文

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

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 方法时记录永远不会保存?为什么?
已编辑:添加了我的控制器。我在显示操作时调用 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

I was hoping someone could explain to me why i can't save new record?

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

My question is when i call update_view_posts method record is never save? Why?
EDITED: Added my controller. I'm calling update_view_posts on show action.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

喜爱皱眉﹌ 2024-10-14 21:46:18

也许你想要:

belongs_to :post

而不是

belongs_to :posts

Maybe you want:

belongs_to :post

instead of

belongs_to :posts
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文