如何从控制器返回JSON或Ruby哈希?

时间:2012-06-07 12:07:38

标签: ruby-on-rails

请在控制器中考虑以下方法:

def get_navigation_from_session
  respond_to do |format|
    format.json { render json: session[:navigation]}
  end
  return session[:navigation]
end

我想要它做的是响应Ajax调用并发送导航哈希,如果它被要求它。如果没有,我只是希望它将哈希返回到需要它的ruby代码。这显然不起作用。如何修复上述方法来实现这一目标?

谢谢

1 个答案:

答案 0 :(得分:0)

# this is your action method, supposed to be called via your request cycle with rendering
def get_navigation_from_session
  respond_to do |format|
    format.json { render json: get_navigation_hash_from_session }
  end
end

# a getter - maybe higher up in controller hiararchy
def get_navigation_hash_from_session
  session[:navigation]
end