0

我正在努力尝试弄清楚如何在 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 对象?

4

2 回答 2

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
于 2012-12-29T18:37:27.430 回答
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 可能来自用户的对话,因此请设置 Conversation belongs_to :user

于 2012-12-29T11:52:05.430 回答