开发者

How to get id of the saved record in Ruby on Rails

I am doing this from the console but I'd like to do this in my code too. Basically I am trying to add a record to the table and then get the id back.

>> @record = Physician.create(:pname => "someone2")
=> #<Physician id: nil, pname: "someone2", pg开发者_运维问答roup: nil, created_at: nil, updated_at: nil, userid: nil, storeid: nil, licexpdate: nil, address: nil>
>> @record.save
=> false
>>


If @record.save returns false, the item wasn't saved and it doesn't have an ID. Use @record.errors.full_messages to see what went wrong


When you successfully save your object, you can access its ID property and get what you need.


Before creating new record make sure that you are providing values for all mandatory columns. If @record.save returns true it means record saved successfully. Get id of it using @record.id


@record=Record.create(:name=>'vidur')
last_record_save_id=Record.last.id
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜