0
class Book < ActiveRecord::Base
  belongs_to :owner, polymorphic: true
end

class User < Active record::Base
  has_many :books, as: :owner
end

Now the Book has three fields - name, owner_id and owner_type. Now I need to search for the name of the user through books.

Something like this ..

Book.includes(:user).where("user_name LIKE ?","bla")

can anyone help me this?

gates
  • 4,465
  • 7
  • 32
  • 60

1 Answers1

0

If you do this:

 Book.includes(:owner)

Can not eagerly load the polymorphic association

You will get this error above.

you need to define the relationship between Book and User

 class Book < ActiveRecord::Base
      belongs_to :owner, polymorphic: true
      belongs_to :user, foreign_key: 'owner_id', conditions: "owner_type = 'User'"
 end

See here

Community
  • 1
  • 1
孙悟空
  • 1,215
  • 1
  • 11
  • 26