简体   繁体   中英

Rails 5 Association id is set to nil

I have upgraded our product from Rails 2.3.48 to Rails 5.2.

In Rails 2

company = Company.first
User.new(company_id: company)
#<User id: nil, company_id: 1

In Rails 5

company = Company.first
User.new(company_id: company)
#<User id: nil, company_id: nil

In Rails 5, Id is set to nil if association_id column is assigned to object.I search alot and not able to find anything Is there any way to ass this behaviour again.

PS: I can not change company to company.id OR company_id to company in my code base because of product is very big.

This is not odd at all. The company_id= setter takes an id and not a record instance.

If you want to assign a record use the company= setter.

irb(main):001:0> company = Company.first
  Company Load (0.6ms)  SELECT "companies".* FROM "companies" ORDER BY "companies"."id" ASC LIMIT $1  [["LIMIT", 1]]
=> #<Company id: 1, name: "E Corp", created_at: "2019-12-10 13:36:21", updated_at: "2019-12-10 13:36:21">
irb(main):002:0> User.new(company: company)
=> #<User id: nil, company_id: 1, created_at: nil, updated_at: nil>

Rails 2 was released in 2007 and the framework was still quite immature at that point, Rails 5 was released in 2015 so the number of changes and incompatibilities is huge. In this case Rails 2 was probably far to lax and just called company= for you.

Interestingly Rails just calls #to_i on whatever you pass if the primary key is a integer column.

class Company < ApplicationRecord
  def to_i
    id
  end
end

irb(main):002:0> User.new(company_id: company)
=> #<User id: nil, company_id: 1, created_at: nil, updated_at: nil>
irb(main):003:0> User.new(company_id: "abcd12345")
=> #<User id: nil, company_id: 0, created_at: nil, updated_at: nil>
irb(main):004:0>  User.new(company_id: "123ABCD4")
=> #<User id: nil, company_id: 123, created_at: nil, updated_at: nil>

Not that I would really recommend this though. Use a search and replace and fix the broken code instead of relying a bad hack.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM