belongs_to with :class_name option fails belongs_to with :class_name option fails ruby-on-rails ruby-on-rails

belongs_to with :class_name option fails


class User < ActiveRecord::Base  has_many :books, :foreign_key => 'author_id'endclass Book < ActiveRecord::Base  belongs_to :author, :class_name => 'User', :foreign_key => 'author_id', :validate => trueend

The best thing to do is to change your migration and change author_id to user_id. Then you can remove the :foreign_key option.


It should be

belongs_to :user, :foreign_key => 'author_id'

if your foreign key is author id. Since you actually have User class, your Book must belong_to :user.


migration

t.belongs_to :author, foreign_key: { to_table: :users }

working on rails 5