简体   繁体   English

如何从Rails模型向控制器发出PUT请求?

[英]How to make a PUT request from a Rails model to controller?

I want to update model via PUT request in Rails app. 我想在Rails应用程序中通过PUT请求更新模型。 What would be the best way to do that? 最好的方法是什么?

Basically I have: 基本上我有:

def method
  ...
  @relation = Relation.find(34)
  @relation.name = "new_name"
  @relation.save
end

This gives me errors in SQLite ("cannot start a transaction within a transaction"). 这给了我SQLite中的错误(“无法在事务中启动事务”)。

Switching to put/post should I guess save the problem.. What would be the right way to do it? 切换到put / post我应该猜测保存问题..什么是正确的方法呢?

So after some time, I actually found the solution. 所以过了一段时间,我实际上找到了解决方案。 Here is the code for the Resque worker, that updates the Relation model via PUT. 以下是Resque worker的代码,它通过PUT更新Relation模型。 Using this method I don't get SQLite busy exception errors. 使用此方法,我不会得到SQLite繁忙的异常错误。

class VideoCollector
  def self.perform(rel_id)
    @relation = Relation.find_by_id(rel_id)
    @url = Rails.application.routes.url_helpers.relation_url(@relation)
    @uri = URI(@url)
    @body ={"collected" => "true"}.to_json
    request = Net::HTTP::Put.new(@uri.path, initheader = {'Content-Type' =>'application/json'})
    request.body = @body
    response = Net::HTTP.new(@uri.host, @uri.port).start {|http| http.request(request) }
  end
end

Maybe that will be useful to someone. 也许那对某人有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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