【问题标题】:Rails table-less model or a better wayRails 无表模型或更好的方法
【发布时间】:2013-06-07 16:42:06
【问题描述】:

我正在使用 Rails 3.2.12

我有一个模型A 和一个名为a 的表。我需要标记a_details,这是一组基于A 类型的属性。 a_details 没有没有表。它是即时制作的。在 show 方法中,我调用了一个方法 getAdetails,在响应中,我将 AA_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


【解决方案1】:

使用 :methods 选项怎么样?

render json: @objects.as_json(include:'creator', methods:'getADetails')

来自http://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html#method-i-as_json

编辑返回一个数组

【讨论】:

  • 这适用于一个对象,可以在索引方法中对一组对象执行此操作。
  • 当然,编辑它以返回一个数组。这是你要找的吗?
  • 但这仍然不能解决在每个 a 对象上调用 getDetails 的问题,对吧?@a_detail = @a.getADetails
  • 够了,现在怎么样?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多