I'd like to get the id
of the data I just saved in activerecord
, but I can't google it (only other information hits), so please let me know.
Image
data=User.create(:name=>hoge)
data.id#ID of the data you just created
Also, please let me know the search words for this information to be a hit.
Additional information
data.attributes['id']
was able to retrieve it.
Is there any problem with this way?
As long as I tried using the rails console at hand, I was able to get an id in the form of data.id
.
irb(main): 001:0>c=Company.create:name=>'hoge'
=>#<Company id:4, name: "hoge", created_at: "2015-02-0203:53:58", updated_at: "2015-02-0203:53:58" >
irb(main): 002:0>c.id
=>4
Perhaps there is a validation error somewhere?
#name is required
irb(main): 004:0>c=Company.create:name=>'
=>#<Company id:nil,name:",created_at:nil,updated_at:nil>
irb(main): 005:0>c.id
=>nil
irb(main): 006:0>c.valid?
=>false
irb(main): 007:0>c.errors
=>#<ActiveModel::Errors:0x007ffc5b8646d8@base=#<Company id:nil,name:",created_at:nil,updated_at:nil,@messages={:name=>["US>" }>
If the id cannot be retrieved, check the return value of data.valid?
.
false
has a validation error and cannot be saved.
Check data.errors
for the contents of the error.
I was able to retrieve it with data.attributes ['id'].
Is there any problem with this way?
In my case, data.attributes['id']
is not the same way to retrieve it, most of the time it is retrieved from data.id
.
data.attributes['id']
is probably not the only thing you can get, so you should investigate the root cause.
Just in case.
class User<ActiveRecord::Base
defined
end
end
user=User.cerate(nane:'nazka')
=>#<User:1,name:"nazka">
user.id
=>nil
user.attributes ['id']
=>1
Are there any id methods defined?
Maybe if you do User.first.id ('hogehoge'...) or something like that,
ArgumentError: wrong number of arguments (1 for 0)
It would be an error like from...activerecord-4.1.9/lib/active_record/... which would be an error in the gem...What do you think?
※ If possible, please let me know what adapter you are using.
© 2024 OneMinuteCode. All rights reserved.