简体   繁体   English

JSON中的url_for用于模型

[英]url_for in JSON for model

Before going any further, I have googled this. 在继续之前,我已经用谷歌搜索了。 I do know the arguments for why you shouldn't have url_for located in the model as this seemingly violates the MVC paradigm. 我确实知道为什么不应该在模型中放置url_for的论点,因为这似乎违反了MVC范式。 In this instance I disagree as this is functioning more as an API for some resources, rather than as a UI. 在这种情况下,我不同意,因为它更多地充当某些资源的API,而不是UI。

I have created a custom responder, and am returning a JSON object which looks like this per request: 我创建了一个自定义响应器,并且正在返回一个JSON对象,每个请求看起来像这样:

  obj = {
    json: resource.as_json,
    request_url: params[:id] ? resource_url : collection_url,
    partial: get_partial(:partial, options),
    flash: flash,
    flash_partial: get_partial(:flash, options),
    user: @current_user,
    status: response.status,
  }

I want each of the objects the controller responds with (using respond_with) to have a url enclosed so that on the client side I can easily keep track of where to send additional requests for a given object (in this case grabbing different view representations depending on which widget has subscribed to that object's state). 我希望控制器响应的每个对象(使用response_with)都包含一个URL,以便在客户端上,我可以轻松地跟踪向给定对象发送其他请求的位置(在这种情况下,根据哪个小部件已订阅该对象的状态)。

I think the best way to to do this is on the model side, as that seems to be the way Rails wants it. 我认为做到这一点的最佳方法是在模型方面,因为这似乎是Rails想要的方式。 Simply adding a function with the url, and then using as_json(:methods => :url). 只需使用url添加一个函数,然后使用as_json(:methods =>:url)。 Unfortunately, url_for is not available on the model side, and I haven't been able to find a Rails3.1 compatible way of including it into ActiveRecord::Base. 不幸的是,url_for在模型端不可用,而且我还没有找到与Rails3.1兼容的方法将其包含在ActiveRecord :: Base中。

class << ActiveRecord::Base
  def url
    url_for self
  end
end

Model.new.as_json(:includes => :url)

I'm open to alternative suggestions as well. 我也欢迎其他建议。

This seems to work... It's a bit of a hack IMO: 这似乎可行... IMO有点黑:

class << ActiveRecord::Base
  include Rails.application.routes.url_helpers
  include ActionDispatch::Routing::UrlFor

  def default_url_options
    { :host => 'localhost:3000' }
  end

  def url
    url_for(self)
  end

  def as_json options
    super options.merge(:methods => :url)
  end
end

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

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