如何在rails中构建数据结构,以便我可以像这样迭代它

时间:2012-12-29 11:46:32

标签: ruby-on-rails ruby

我正在努力尝试弄清楚如何在ruby中构建数据结构。

在我看来,我希望像这样迭代它

<% @conversations.each do |conversation| %>
    <%= "#{conversation.meta.subject} - #{conversation.meta.created_at} %>

    <% conversation.messages.each do |message| %>
         <%= message.name %>
    <% end %>

<% end %>

消息来自活动记录查询

@messages = Message.find_by_name('john')

Meta是这样的哈希

@meta = { 'subject ' => 'John Messages', 'created_at' => '2012-12-28 10:20:55.230286' }

如何将其转换为我需要的@conversations对象?

2 个答案:

答案 0 :(得分:1)

我没有测试它。尝试并发布反馈。

class Conversation
  attr_reader :name

  class Meta
    attr_accessor :subject, :created_at
    def initialize(attributes = {})
      attributes.each do |key, value|
        send("#{key}=", value)
      end
    end
  end

  def initialize(name)
    @name = name
    messages # preload
  end

  def messages
    @messages ||= Message.where(:name => name).order("created_at") # .find_by_name returns a single object, but you waiting for an Array, so use .where
  end

  def default_meta_attributes
    {:subject => "#{name} Messages", :created_at => messages.last.created_at}
  end

  def meta(attrs={})
    @meta ||= Meta.new(attrs.blank? ? default_meta_attributes : attrs)
  end

end

# test

@conversations = []
@conversations << Conversation.new("John")

@conversations.each do |conversation|
  puts conversation.meta.subject
  puts conversation.meta.created_at
  puts "Now conversation messages of #{conversation.name}"
  conversation.messages.each do |message|
    puts message.name
  end
end

答案 1 :(得分:0)

Conversation
 - subject : string

has_many :messages

Message
 - name : string

belongs_to :conversation

更改此行:

<%= "#{conversation.meta.subject} - #{conversation.meta.created_at} %>

<%= "#{conversation.subject} - #{conversation.created_at} %>

@conversations可能来自用户的对话,因此请将对话归属于:用户