Skip to content

Instantly share code, notes, and snippets.

@westonplatter
Created March 9, 2013 01:58
Show Gist options
  • Select an option

  • Save westonplatter/5122141 to your computer and use it in GitHub Desktop.

Select an option

Save westonplatter/5122141 to your computer and use it in GitHub Desktop.
Code snippet showing how to search for polymorpic related Rails Active Record relying on Rails 4 SQL duct typing magic!
class Post < ActiveRecord::Base
has_many :comments, as: commentable
# attributes, :title
end
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true
end
post = Post.create! title: 'new_post'
comment = post.comments.create
Comment.where(commentable: post)
# In Rails 3.2.12, this did not return the instantiated Post object,
# but in Rails 4, this does return the Post instance
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment