首页 文章

使用v0.9.3创建url属性时,Active Model Serializers出错

提问于
浏览
1

我正在尝试在AMS中做一些超级简单的事情,我在其中生成对象的url属性,如下所示:

class DeckSerializer < ActiveModel::Serializer
  attributes :id, :title, :description, :url

  has_one :user
  has_many :cards

  def url
    deck_url(object)
  end
end

但是,我收到以下错误:

ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true

我目前正在使用Rails 4.2.0和AMS 0.9.3

有谁知道发生了什么?

3 回答

  • 1

    这是解决这个问题的DIY方法 . 在模型上创建一个字段以存储URL . 然后在保存对象后,使用手动生成的URL更新它 . 这是我如何解决它 .

    if @questionsolution.save
    generatedurl = 'http://localhost:3000/questionsolutions/' + @questionsolution.id.to_s
            @questionsolution.update(solutionurl: generatedurl)
    end
    

    然后你可以从资源direclty获取url,而不依赖于活动模型序列化程序来为你完成 .

  • 0

    原来这是一个已知的错误:

    https://github.com/rails-api/active_model_serializers/issues/573

    我将AMS版本切换到0.8.3,一切正常 . 虽然不是一个完整的解决方案,但它暂时有效 . 有兴趣听取他人的想法

  • 0

    你必须把 Rails.application.routes.default_url_options[:host] = 'localhost:3000' 放在 config/environments/development.rb

相关问题