Skip to content

Instantly share code, notes, and snippets.

@alexch
Created November 18, 2014 19:02
Show Gist options
  • Save alexch/dcb5b15570694ca220d1 to your computer and use it in GitHub Desktop.
Save alexch/dcb5b15570694ca220d1 to your computer and use it in GitHub Desktop.
class Animal < ActiveRecord::Base
end
class Bark < ActiveRecord::Base
belongs_to :barker, class: Animal, polymorphic: true
before_save { barker.type == "Dog" }
end
class Cat < Animal
end
class Dog < Animal
end
@alexch
Copy link
Author

alexch commented Nov 18, 2014

>> Bark.create! barker: Dog.first
  Dog Load (0.8ms)  SELECT  "animals".* FROM "animals"  WHERE "animals"."type" IN ('Dog')  ORDER BY "animals"."id" ASC LIMIT 1
  SQL (0.7ms)  INSERT INTO "barks" ("barker_id", "barker_type", "created_at", "updated_at") VALUES (?, ?, ?, ?)  [["barker_id", 1], ["barker_type", "Animal"], ["created_at", "2014-11-18 19:03:53.858921"], ["updated_at", "2014-11-18 19:03:53.858921"]]
=> #<Bark id: 8, barker_id: 1, barker_type: "Animal", created_at: "2014-11-18 19:03:53", updated_at: "2014-11-18 19:03:53">


>> Bark.create! barker: Cat.first
  Cat Load (0.5ms)  SELECT  "animals".* FROM "animals"  WHERE "animals"."type" IN ('Cat')  ORDER BY "animals"."id" ASC LIMIT 1
ActiveRecord::RecordNotSaved: ActiveRecord::RecordNotSaved

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment