Created
March 9, 2013 01:58
-
-
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!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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