【发布时间】:2013-06-07 16:42:06
【问题描述】:
我正在使用 Rails 3.2.12。
我有一个模型A 和一个名为a 的表。我需要标记a_details,这是一组基于A 类型的属性。 a_details 没有没有表。它是即时制作的。在 show 方法中,我调用了一个方法 getAdetails,在响应中,我将 A 和 A_details 作为 JSON 对象传递。
这在index 方法中变得很棘手,因为会有很多,而且我不认为我想循环遍历每个对象来创建一个数组对象并渲染它们。我正在考虑无表模型,并在渲染为 JSON 时使用 :include 方法使用名为 activerecord_association 的 gem。我在想,有没有更好的方法呢?
# show method.
a = A.new
@a_detail = @a.getADetails
response = {:notification => @a.as_json(:include => :creator), :a_detail => @a_detail}
#index
respond_to do |format|
format.html # index.html.erb
format.json { render json: @objects.as_json(:include => :creator) }
end
【问题讨论】:
-
所以,为了缩小问题的范围——您想为 Ruby 对象数组创建 JSON,对吧?
-
是的!但以更好的方式,我希望它成为对象 A 本身的一部分。就像创建者在对象 A 中的样子。
标签: ruby-on-rails activerecord ruby-on-rails-3.2