0

Suppose in Ruby on Rails, there is a return of JSON data:

render :json => array_of_purchases

and this array_of_purchases contains many Purchase objects, each one with a product_id. Now if we want to add a property to the JSON returned, so that each Purchase object will also include its Product object data:

"product": { "id": 123, "name": "Chip Ahoy", image_file: "chip_ahoy.jpg", ... etc }

Then how can a new instance variable be added inside this controller action?

It might be

def get_data
  #  getting data ...
  class Purchase
    attr_accessor :product   # adding an instance variable
  end
  array_of_purchases.each {|p| p.product = Product.find(p.product_id)}
  render :json => array_of_purchases
end

but adding an instance variable to a class within this method (which is a controller action) won't work.

Update: this is assuming 1 Order has many Purchases, and 1 Purchase is a product and a quantity. (maybe some system call it an order line?)

4

3 回答 3

1

我可以假设一个Purchasehas_manyProducts吗?

Rails 提供了一些有用的选项。to_json

class Purchase
  def to_json
    super :include => :products
  end
end

编辑:你能发布你的模型是什么样的吗?目前尚不清楚您要做什么。

请记住,在 Ruby 中,您可以动态地为单个对象定义方法。

def purchase.to_json
  super :include => :products
end
于 2010-08-19T02:12:12.473 回答
1

假设您的Purchase模型与Product模型有关联:

class Purchase
  belongs_to :product
end

class Product
  has_many :purchases
end

render :json => array_of_purchases.to_json(:include => :product)

purchases您可以在创建数组时进一步优化这种预先加载的产品。

于 2010-08-19T08:39:16.963 回答
0

我假设一个采购类。也许是 ActiveRecord 模型?

# in Controller

def show_full_display
  purchases = Purchase.find_all_by_customer_id(session.customer_id,
                 :include => :product)
  render :json => purchases.map{|p| p.full_display}.to_json  # convert to json
end

# in Purchase class
# fields include
#   id
#   customer_id
#   product_id
#        
belongs_to :product

def full_display
   # returns a hash for use by the full_display clients
   # Will be converted to JSON
   {"id" => id, "name" => product.name, "image_file" => product.image}
end

注意:类 Purchase 的 full_display 方法返回一个 ruby​​ 哈希。然后控制器将散列数组转换为 JSON 对象数组。(Javascript 使用对象作为哈希值。)

full_display 方法可以在控制器而不是模型中。我将其放入模型中以进行更好的测试等。这是“瘦控制器,胖模型”的想法。

于 2010-08-19T02:06:13.183 回答