developer tip

Rails에서 to_json을 재정의하는 방법은 무엇입니까?

optionbox 2020. 8. 31. 07:40
반응형

Rails에서 to_json을 재정의하는 방법은 무엇입니까?



최신 정보:

이 문제는 제대로 조사되지 않았습니다. 진짜 문제는 render :json.

원래 질문의 첫 번째 코드 붙여 넣기는 예상 결과를 산출합니다. 그러나 여전히 경고가 있습니다. 이 예를 참조하십시오.

render :json => current_user

이다 NOT 과 동일

render :json => current_user.to_json

, User 개체와 연결된 메서드를 render :json자동으로 호출하지 않습니다 to_json. 실제로 모델에서 to_json재정의되는 경우 아래 설명 된 내용이 생성 됩니다.Userrender :json => @userArgumentError

요약

# works if User#to_json is not overridden
render :json => current_user

# If User#to_json is overridden, User requires explicit call
render :json => current_user.to_json

이 모든 것이 나에게는 어리석은 것 같습니다. 이것은 유형 이 지정 될 때 render실제로 호출되지 않는다는 것을 알려주는 것 같습니다 . 누군가 여기서 실제로 무슨 일이 일어나고 있는지 설명 할 수 있습니까?Model#to_json:json

이 문제를 해결할 수있는 모든 genii는 다른 질문에 답할 수 있습니다. Rails에서 @ foo.to_json (options) 및 @ bars.to_json (options)을 결합하여 JSON 응답을 빌드하는 방법


원래 질문 :

나는 다른 몇 가지 예를 보았지만 내가 찾고있는 것을하지 않습니다.

노력하고있어:

class User < ActiveRecord::Base

  # this actually works! (see update summary above)
  def to_json
    super(:only => :username, :methods => [:foo, :bar])
  end

end

나는 얻고 ArgumentError: wrong number of arguments (1 for 0)에서

/usr/lib/ruby/gems/1.9.1/gems/activesupport-2.3.5/lib/active_support/json/encoders/object.rb:4:in `to_json

어떤 아이디어?


하나의 매개 변수 인 해시 로 재정의해야하기 ArgumentError: wrong number of arguments (1 for 0)때문에 얻는 to_jsonoptions입니다.

def to_json(options)
  ...
end

의 긴 설명 to_json, as_json및 렌더링 :

ActiveSupport 2.3.3에서는 as_json발생한 문제와 같은 문제를 해결하기 위해 추가되었습니다. json 생성 은 json의 렌더링분리되어야합니다 .

이제 언제든지 to_json객체에서 as_json호출되고 데이터 구조를 생성하기 위해 호출 된 다음 해당 해시가를 사용하여 JSON 문자열로 인코딩됩니다 ActiveSupport::json.encode. 이것은 객체, 숫자, 날짜, 문자열 등 모든 유형에 대해 발생합니다 (ActiveSupport 코드 참조).

ActiveRecord 개체는 동일한 방식으로 작동합니다. as_json모든 모델의 속성을 포함하는 해시를 생성 하는 기본 구현이 있습니다. 원하는 JSON 구조를 생성하려면 모델에서 재정의해야합니다as_json . as_jsonold와 마찬가지로 to_json는 선언적으로 포함 할 속성과 메서드를 지정할 수있는 옵션 해시를 사용합니다.

def as_json(options)
  # this example ignores the user's options
  super(:only => [:email, :handle])
end

In your controller, render :json => o can accept a string or an object. If it's a string, it's passed through as the response body, if it's an object, to_json is called, which triggers as_json as explained above.

So, as long as your models are properly represented with as_json overrides (or not), your controller code to display one model should look like this:

format.json { render :json => @user }

The moral of the story is: Avoid calling to_json directly, allow render to do that for you. If you need to tweak the JSON output, call as_json.

format.json { render :json => 
    @user.as_json(:only => [:username], :methods => [:avatar]) }

If you're having issues with this in Rails 3, override serializable_hash instead of as_json. This will get your XML formatting for free too :)

This took me forever to figure out. Hope that helps someone.


For people who don't want to ignore users options but also add their's:

def as_json(options)
  # this example DOES NOT ignore the user's options
  super({:only => [:email, :handle]}.merge(options))
end

Hope this helps anyone :)


Override not to_json, but as_json. And from as_json call what you want:

Try this:

def as_json 
 { :username => username, :foo => foo, :bar => bar }
end

참고URL : https://stackoverflow.com/questions/2572284/how-to-override-to-json-in-rails

반응형