Rails respond_with 使用上的一些问题

zhbinx · 2013年03月25日 · 最后由 vkill 回复于 2013年03月26日 · 7533 次阅读

刚才在试着学习respond_to以及respond_with这 2 个方法 有几个疑问,麻烦大家帮忙

1.google 了一上午,资料比较少,求大家推荐点

2.respond_torespond_with适用场景有什么区别

respond_to do |format|
    format.html
    format.json { render :json => @json }
end
respond_to :html, :xml, :json

respond_with(@json) 

在我看来,respond_with()看上去比较简单点,是不是都可以用这个?

3.respond_to需要返回多个 ActiveRecord 时候该怎么写 当返回 2 个有关联的 ActiveRecord 时候,可以respond_with(@json,:include=>:some_record),返回的 json 包含了@json以及:some_record,但是在 2 个毫无关系的 ActiveRecord 时,我该怎么写

@json1 = Json.all
@json2 = AnotherJson.all
respond_wih(???)

4.respond_to 只是用来展示的吗?我可以用他做一些交互动作么 我可以不可以往 json 地址中传一些参数,来完成如 create、search 的 action 呢?

我平时发帖提问比较多,但是我肯定是自己先花自己小时去看看的…… 希望不是我的原因,促成新版规的出现…… 😱 谢谢大家帮忙回答下

2 确实是都可以用 respond_with

下面是一些用法

这个就是很经典的那种写法的简写

@message.new(params[:message])
@message.save
respond_with @message, :location => [:messages], :action => :new

有 namespance 时

respond_with :admin, @repository
respond_with :admin, @repository, :location => root_path

使用嵌套路由时

respond_with @post, @comment

当然,如果你想自定义 response code 时,使用类似这个方法 https://github.com/nesquena/rabl/wiki/Response-Codes

如果你想自定义 flash,参考 https://github.com/plataformatec/responders

配合 respond_to 就可以定义 action 使用 哪些 template

3 respond_with 后面传递那个 resource 仅仅是用 resource.errors.empty? 来判断成功和失败的

4 在 search 完成后的 template 里直接用 controller 里的 @xx 就好了,不需要传递

需要 登录 后方可回复, 如果你还没有账号请 注册新账号