我无法确定如何使用引用父类的has_many / belongs_to关系为我的类设置工厂。它的设置如下。
class PrivateMessage < ActiveRecord::Base
attr_accessible :body, :read_at, :title, :receiver_id, :sender_id, :conversation_id
belongs_to :sender, class_name: 'Profile', foreign_key: 'sender_id'
belongs_to :receiver, class_name: 'Profile', foreign_key: 'receiver_id'
belongs_to :conversation, :class_name => 'PrivateMessage' # Reference to parent message
has_many :replies, :class_name => 'PrivateMessage', :foreign_key => 'conversation_id',
order: 'created_at DESC'
我对如何处理这个问题感到有些不知所措,或者在这种情况下我甚至应该使用工厂。在我的控制器中,如果conversation_id正常为nil(使用profile.sent_messages.build),我会创建一条消息,否则如果发送者/接收者之间有任何消息,我引用父消息,并使用parent_message.replies.build来构建它
我认为我需要某种带有after_build挂钩的嵌套工厂,但我无法完全理解如何做到这一点。像这样的东西?我在上面定义私人消息的地方。这显然是错的,但我是在正确的轨道上吗?如何使用after_build块引用父消息?
factory :private_message do
sequence(:body) { |n| "This is a body of a message :) #{n}" }
association :sender
association :receiver
end
factory :reply do
association :private_message
sequence(:body) { |n| "This is the body of a reply #{n}" }
association :sender
association :receiver
after_build do |private_message|
private_message.replies << :reply
end
end
答案 0 :(得分:0)
如果我理解这个问题......
这样的事情有意义吗?
factory :private_message do
sequence(:body) { |n| "This is a body of a message :) #{n}" }
association :sender
association :receiver
factory :reply do
sequence(:body) { |n| "This is the body of a reply #{n}" }
association :conversation
end
end
您可以让自己的生活更轻松地将对话分解为单独的模型......