ActiveRecord belongs_to association does not save

2019-09-14 05:30发布

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!

2条回答
祖国的老花朵
2楼-- · 2019-09-14 05:41

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
}
查看更多
走好不送
3楼-- · 2019-09-14 05:56

Try this instead:

record.ns_attributes.create!(key: "artist", value: "bob dylan")
查看更多
登录 后发表回答