Skip to content

Instantly share code, notes, and snippets.

@Kukunin
Created September 17, 2014 19:48
Show Gist options
  • Save Kukunin/a57ecea9d40e65a2de07 to your computer and use it in GitHub Desktop.
Save Kukunin/a57ecea9d40e65a2de07 to your computer and use it in GitHub Desktop.
Rails belongs_to, accepts_nested_attributes_for and not typical model name bug
unless File.exist?('Gemfile')
File.write('Gemfile', <<-GEMFILE)
source 'https://rubygems.org'
gem 'rails', github: 'rails/rails'
gem 'arel', github: 'rails/arel'
gem 'rack', github: 'rack/rack'
gem 'i18n', github: 'svenfuchs/i18n'
gem 'sqlite3'
GEMFILE
system 'bundle'
end
require 'bundler'
Bundler.setup(:default)
require 'active_record'
require 'minitest/autorun'
require 'logger'
# Ensure backward compatibility with Minitest 4
Minitest::Test = MiniTest::Unit::TestCase unless defined?(Minitest::Test)
# 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 :models do |t|
t.integer :policy_id, null: false
end
create_table :policies_property do |t|
t.string :name, null: false
end
end
module Policies
end
class Policies::Property < ActiveRecord::Base
self.table_name = "policies_property"
has_one :model, inverse_of: :policy
end
class Model < ActiveRecord::Base
validates :policy, presence: true
belongs_to :policy, inverse_of: :model, class_name: Policies::Property
accepts_nested_attributes_for :policy
end
class BugTest < Minitest::Test
def test_accept_nested_attributes_for
Model.create! policy_attributes: { name: 'Hello Kity' }
end
end
@Kukunin
Copy link
Author

Kukunin commented Sep 17, 2014

has_one :model, inverse_of: :policy, foreign_key: :policy_id fix the problem

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