Skip to content

Instantly share code, notes, and snippets.

@mfazekas
Created June 27, 2014 05:38
Show Gist options
  • Save mfazekas/c13d76b027ca3ee6923e to your computer and use it in GitHub Desktop.
Save mfazekas/c13d76b027ca3ee6923e to your computer and use it in GitHub Desktop.
accepts_nested_attributes_for has_many and new association with ids.
unless File.exist?('Gemfile')
File.write('Gemfile', <<-GEMFILE)
source 'https://rubygems.org'
gem 'rails', github: 'rails/rails'
gem 'arel', github: 'rails/arel'
gem 'sqlite3'
GEMFILE
system 'bundle'
end
require 'bundler'
Bundler.setup(:default)
require 'active_record'
require 'minitest/autorun'
require 'logger'
# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table :posts do |t|
end
create_table :comments do |t|
t.integer :post_id
end
end
class Post < ActiveRecord::Base
has_many :comments
accepts_nested_attributes_for :comments
end
class Comment < ActiveRecord::Base
belongs_to :post
end
class BugTest < Minitest::Test
def test_association_stuff
comment = Comment.create!
post = Post.new(comments_attributes:{"0"=>{"id"=>comment.id}})
post.save!
assert_equal 1, post.comments.count
assert_equal post.id, Comment.first.post.id
assert_equal comment.id,post.comments.first.id
assert_equal 1, Comment.count
end
end
@bertBruynooghe
Copy link

it seems a similar issue was raised on http://stackoverflow.com/questions/18835422/rails-4-nested-attributes-couldnt-find-tag-with-id-for-person-with-id/19863805#comment73485730_19863805

Not sure why you wrote the gist: did the test pass (in Rails 4)? Did you try agains Rails 5?

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