wpp
wpp

Reputation: 7333

ActiveRecord belongs_to association does not save foreign_key (Rails 4)

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).

Any clues as to whats going on are appreciated!

Upvotes: 0

Views: 747

Answers (2)

Jeremy
Jeremy

Reputation: 122

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:

NsAttribute::GeneratedFeatureMethods.module_eval %Q{
  def create_record(*args, &block)
    super
  end
}

Upvotes: 1

user2503775
user2503775

Reputation: 4367

Try this instead:

record.ns_attributes.create!(key: "artist", value: "bob dylan")

Upvotes: 0

Related Questions