4

我有一个Post和一个User模型。我正在尝试添加一种Bookmark模式,以便用户可以为帖子添加书签。我正在使用join model

架构.rb:

create_table "bookmarks", :force => true do |t|
  t.integer  "bookmarker_id"
  t.integer  "bookmarked_id"
  t.datetime "created_at",    :null => false
  t.datetime "updated_at",    :null => false
end

书签.rb:

class Bookmark < ActiveRecord::Base
  attr_accessible :bookmarked_id

  belongs_to :bookmarker, class_name: "User"
  belongs_to :bookmarked, class_name: "Post"

  validates :bookmarker_id, presence: true
  validates :bookmarked_id, presence: true
end

post.rb:

has_many :bookmarks, :dependent => :destroy
has_many :bookmarkers, :through => :bookmarks

用户.rb:

has_many :bookmarks, :dependent => :destroy
has_many :bookmarked_posts, :through => :bookmarks, source: :bookmarked 

我试图在终端中测试关联,但我得到了这个:

1.9.3-p0 :007 > user.bookmarks
  Bookmark Load (0.4ms)  SELECT "bookmarks".* FROM "bookmarks" WHERE "bookmarks"."user_id" = 1
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: bookmarks.user_id: SELECT "bookmarks".* FROM "bookmarks"  WHERE "bookmarks"."user_id" = 1

可能是什么问题呢?

4

2 回答 2

6

您没有指定foreign_key,异常明确表示

no such column: bookmarks.user_id

只需添加

has_many :bookmarks, :foreign_key => 'bookmarker_id'
于 2012-12-24T14:08:21.930 回答
1

没有外键书签

执行以下操作;

rails g migration add_user_id_to_bookmarks user_id:integer

然后做

has_many :bookmarks, :foreign_key => 'bookmarker_id'
于 2012-12-24T14:20:24.273 回答