Wrong number of arguments in as_json [`timeout` method is reserved!]

回眸只為那壹抹淺笑 提交于 2019-12-25 04:14:22

问题


I get an error in Rails that is related to one of my models, let's call it Unit. The following code produces an error:

format.json { render :json => @units.as_json }

The error is about wrong number of parameters (0 of 1).


回答1:


I believe what you want is;

def scheme
  @object = MonitoringObject.restricted_find params[:id], session[:client]

  @units = Unit.where("object_id = ?", @object.id)

  respond_to do |format|
    format.html
    format.json { render :json => @units[0] }
  end
end

Or, if you have your relationships set up between the MonitoringObject and Unit models correctly,

def scheme
  @object = MonitoringObject.restricted_find params[:id], session[:client]
  @units = @object.units

  respond_to do |format|
    format.html
    format.json { render :json => @units[0] }
  end
end

You're supplying it with an :except parameter that's empty.

You'll use an :except condition if there are some attributes you don't want included in the JSON response.

According to the rails guide on views and rendering, you don't need to specify .to_json -- it will be called for you automatically.

It looks to me that the problem may lie in your .restricted_find method somewhere. Can you post the entire stack trace )or link to a github gist that contains it?




回答2:


I solved the problem. From the Rails source:

  module Serialization
    def serializable_hash(options = nil)
      options ||= {}

      attribute_names = attributes.keys.sort
      if only = options[:only]
        attribute_names &= Array.wrap(only).map(&:to_s)
      elsif except = options[:except]
        attribute_names -= Array.wrap(except).map(&:to_s)
      end

      hash = {}
      attribute_names.each { |n| hash[n] = read_attribute_for_serialization(n) } # exception here

      # ...
    end

    alias :read_attribute_for_serialization :send

    # ...
  end

  # ...
end

So the real error is that one of the methods returned by calling e.g. Unit.first.attributes.keys.sort (["dev_id", "flags", "id", "inote", "ip", "location_id", "model_id", "name", "period", "phone", "port", "snote", "timeout"]) expects me to pass an argument to it. This method is timeout, it is some private method Rails monkey patches Object with. So the correct solution to the problem is to rename this attribute to something else.



来源:https://stackoverflow.com/questions/10431077/wrong-number-of-arguments-in-as-json-timeout-method-is-reserved

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!