使用rails响应添加另一个键值

时间:2016-12-20 22:10:32

标签: ruby-on-rails

我有一个房产。酒店拥有许多房间。每个房间都有很多照片。因此,当获得此房产的所有房间时,我希望每个房间都有一个额外的阵列字段,其中包含该房间的图像,以便日后查看。

@property=Property.find(params[:id])
#initialized array for calculations
    @rooms=[]
#creates a photos key as array value 
    @property.rooms.each do |room|
      room=room
#for saving all photos for 1 room
      photos=[]
      room.photos.each do |photo|
        photos.push(photo.image_url(:medium))
      end
#create and add a photos key to the room hash
      room[:photos] << photos
#push the room hash to @rooms instance variable
      @rooms.push(room)
    end

这不起作用

检查时我得到以下错误

  

ActiveModel :: MissingAttributeError:无法写入未知属性   photos

有人能告诉我可能是什么原因吗?在rails中有更好的方法吗?

2 个答案:

答案 0 :(得分:0)

无需手动循环roomsphotos。相反,在模型中建立关系:

# app/models/property.rb
class Property < ActiveRecord::Base
  has_many :rooms
  # ...
end

# app/models/room.rb
class Room < ActiveRecord::Base
  belongs_to :property, inverse_of :rooms
  has_many :photos
  # ...
end

# app/models/photo.rb
class Room < ActiveRecord::Base
  belongs_to :room, inverse_of :photos
  # ...
end

有了这个,你就可以使用点符号:

@property.rooms[0].photos # all the photos of the first room

答案 1 :(得分:0)

终于找到了解决方案。问题是我从活动记录获得的结果不是普通哈希而是模型实例。因此,为了添加属性,我将其转换为json,然后添加了一个新的键值,现在它按预期工作。

#initialized array for calculations
    @rooms=[]
    #for each creates a photos key as array value
    @property.rooms.each do |room|
#for saving all photos for 1 room
      photos=[]
      room.photos.each do |photo|
        photos.push(photo.image_url(:medium))
      end

      room=room.as_json

#create and add a photos key to the room hash
      room['photos']= photos
#push the room hash to @rooms instance variable
      @rooms.push(room.as_json)
    end