Created
September 20, 2014 17:46
-
-
Save markprzepiora/61e7e6a3c06e9b573390 to your computer and use it in GitHub Desktop.
ActiveRecord 4.2 relationship + callback regression
This file contains 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
# Models | |
class Post < ActiveRecord::Base | |
after_save :do_something_to_tags | |
has_many :post_tags, inverse_of: :post | |
has_many :tags, through: :post_tags | |
def do_something_to_tags | |
puts "The following line in Rails 4.2 incorrectly joins on post_id = NULL" | |
puts "(not even proper SQL) even though the post's ID is already set and available" | |
puts "- Post ID: #{id}" | |
puts "- post_tags with join: #{post_tags.joins(:tag).to_a}" | |
puts "\nFurthermore, the post_tags are not yet created" | |
puts "- post_tags: #{post_tags.to_a}" | |
puts "\nThey are only created after this callback" | |
end | |
end | |
class PostTag < ActiveRecord::Base | |
belongs_to :post, inverse_of: 'post_tags' | |
belongs_to :tag, inverse_of: 'post_tags' | |
end | |
class Tag < ActiveRecord::Base | |
has_many :post_tags, inverse_of: :tag | |
end | |
# Migrations (nothing special here) | |
class CreatePosts < ActiveRecord::Migration | |
def change | |
create_table :posts do |t| | |
t.timestamps null: false | |
end | |
end | |
end | |
class CreateTags < ActiveRecord::Migration | |
def change | |
create_table :tags do |t| | |
t.timestamps null: false | |
end | |
end | |
end | |
class CreatePostTags < ActiveRecord::Migration | |
def change | |
create_table :post_tags do |t| | |
t.references :post | |
t.references :tag | |
t.timestamps null: false | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment