This weekend I decided to take Rails 4 for a spin and promptly ran into the following issue:
I have two models (wanted to try an OpenSchema incase you are wondering):
Record
has_many :ns_attributes
NsAttribute
belongs_to :record
Now in the console:
record = Record.create!(name: "blowing in the wind")
nsa = NsAttribute.new(key: "artist", value: "bob dylan", record: record)
#<NsAttribute id: nil, key: "artist", value: "bob dylan", record_id: 4, created_at: nil, updated_at: nil>
irb(main):007:0> nsa.save!
(0.4ms) BEGIN
Record Exists (0.7ms) SELECT 1 AS one FROM "records" WHERE "records"."name" IS NULL LIMIT 1
(0.2ms) COMMIT
=> true
irb(main):008:0> nsa
=> #<NsAttribute id: nil, key: "artist", value: "bob dylan", record_id: nil, created_at: nil, updated_at: nil>
As you can see the record did not get saved (record_id: nil).
- I also tried adding class_name and foreign_key to the belongs_to method without a change.
- Could it be because of of the AR model name? ("record")
- There are no validations on the two models
Any clues as to whats going on are appreciated!
I've got the same problem. It appears to be a bug in Rails 4. Here is the test case:
https://gist.github.com/jemmyw/8163504
And here is the issue:
https://github.com/rails/rails/issues/13522
You can fix it on a per model basis by adding the following snippet below the model that has the record association:
Try this instead: