简体   繁体   English

在Rails控制器中实现erb代码?

[英]Implement erb code in rails controller?

I wanted to render my model to json and include it's nodes when using acts_as_tree. 我想将模型渲染为json,并在使用acts_as_tree时包括其节点。 I found this post and it helped alot: acts_as_tree and to_json or from_json 我发现了这篇文章,并且对很多人有帮助: acts_as_tree和to_json或from_json

My only question is how to implement this in my controller. 我唯一的问题是如何在控制器中实现此功能。 I want to return the json in my controller. 我想在控制器中返回json。

So far I have this: 到目前为止,我有这个:

 respond_to :json, :html

  def index
    @categories = Category.all
    respond_with(@categories)
  end

But before returning @categories I'd like to call this on it: <%= @categories.select { |c| c.root? && !c.leaf? }.collect { |c| category_to_spacetree_json(c) }.to_json.html_safe %> 但是,在返回@categories之前,我想在上面调用它: <%= @categories.select { |c| c.root? && !c.leaf? }.collect { |c| category_to_spacetree_json(c) }.to_json.html_safe %> <%= @categories.select { |c| c.root? && !c.leaf? }.collect { |c| category_to_spacetree_json(c) }.to_json.html_safe %> <%= @categories.select { |c| c.root? && !c.leaf? }.collect { |c| category_to_spacetree_json(c) }.to_json.html_safe %> But it looks like this can only be called from the view. <%= @categories.select { |c| c.root? && !c.leaf? }.collect { |c| category_to_spacetree_json(c) }.to_json.html_safe %>但这似乎只能从视图中调用。

How do I do this from my controller? 如何从我的控制器执行此操作?

Thanks! 谢谢!

Have you tried this? 你有尝试过吗?

In the controller: 在控制器中:

def index
  @categories = Category.all
  respond_with(@categories.select{ |c| c.root? && !c.leaf? }.collect{ |c| category_to_spacetree_json(c) })
end

In the view: 在视图中:

<%= @categories.html_safe %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM