Getting this column: bookmarks in the next many-to-many association

I have a Post and User model. I am trying to add Bookmark mode so that users can add bookmarks. I am using join model :

schema.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 

bookmark.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 

user.rb:

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

I tried to check the association in the terminal, but I get the following:

 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 

What could be the problem?

+4
source share
2 answers

You did not specify foreign_key, the exception is explicitly indicated

 no such column: bookmarks.user_id 

just add

 has_many :bookmarks, :foreign_key => 'bookmarker_id' 
+6
source

No foreign key bookmarks

follow these steps:

 rails g migration add_user_id_to_bookmarks user_id:integer 

then do

 has_many :bookmarks, :foreign_key => 'bookmarker_id' 
+1
source

All Articles