开发者

Setting id on an active resource object

开发者 https://www.devze.com 2023-04-11 18:56 出处:网络
We have to restore a deleted record using active resource with the same id it had before deletion. a = ActiveResourceModel.new

We have to restore a deleted record using active resource with the same id it had before deletion.

a = ActiveResourceModel.new

a.new? # true

a = ActiveResourceModel.new

a.id = 1234

a.new? # false

If the active resource object has开发者_开发问答 id attribute set, it is always considered as a saved object and it always tries to update the record. We had to create a custom post action to set the id to the previous value. Is there any other way of doing this?


the ActiveResource::Base source shows this:

def new?
  id.nil?
end

So you have to override the new? method, or to call the private method create directly

class YourModel < ActiveResource::Base

  def restore
    create
  end

  # or
  def new?
    @some_custom_flag_variable ? true : id.nil?
  end

end

be prepared to handle errrors if the id is already taken, though (who knows ?)

0

精彩评论

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