1

我在建立协会时遇到了麻烦。我的模型定义如下:

class Conversation
  belongs_to :user1
  belongs_to :user2
  has_many :messages
end

我已经定义了这些工厂

factory :user do
  name "name"
end

factory :female, parent: :user do
  gender 'f'
end 

factory :male, parent: :user do
  gender 'm'
end 

factory :message do
  message "message"
  conversation
end

现在我正在尝试像这样创建工厂“conversation_with_messages”

factory :conversation do
    read false
    association :user1, factory: :male
    association :user2, factory: :female    
    factory :conversation_with_messages do

      ignore do
        messages_count 10
      end

      after(:create) do |conversation, evaluator|
        FactoryGirl.create_list(:message, evaluator.messages_count, author: conversation.user1)
      end
    end
  end

但是这样做FactoryGirl.create(:conversation_with_messages)会导致数据库错误,提示 user1_id 列必须不为空。

我想知道为什么这个专栏没有填满,我在这里做错了什么?

4

2 回答 2

1

您是否class_name在对话模型中指定了关系?

class Conversation
  belongs_to :user1, class_name: 'User'
  belongs_to :user2, class_name: 'User'
  has_many :messages
end
于 2013-03-14T14:06:34.623 回答
0

当测试很困难时,请考虑修改您的设计。脑海中浮现出两个想法:

1)必须 Users 有多个Conversations?

如果像 Twitter 的直接消息模型(任意两个用户之间的一个持续对话)这样的东西是可以接受的,那么你可以选择类似的东西:

class Message < ActiveRecord::Base
  belongs_to :sender, class_name: 'User'
  belongs_to :recipient, class_name: 'User'

  default_scope order("created_at DESC")

  def read?
    !self.unread?
  end

  def read_or_unread
    self.unread? ? "unread" : "read"
  end
end

class User < ActiveRecord::Base
  has_many :messages, foreign_key: :recipient_id

  def messages_grouped_by_sender
    msg_ids = messages.select("MAX(id) AS id").group(:sender_id).collect(&:id)
    Message.includes(:sender).where(id: msg_ids)
  end
end

class Conversation

  THEM_TO_ME = "sender_id = :their_id AND recipient_id = :my_id"
  ME_TO_THEM = "sender_id = :my_id AND recipient_id = :their_id"

  def initialize(me, them)
    @me = me
    @them = them
  end

  def them
    @them
  end

  def thread
    Message.where("#{ME_TO_THEM} OR #{THEM_TO_ME}", ids)
  end

  def unread?
    # Checking only the newest message is good enough
    messages_to_me.first.try(:unread)
  end

  def mark_as_read
    messages_to_me.where(:unread => true).update_all(:unread => false)
  end

  def to_or_from_me(message)
    message.sender == @me ? "From" : "To"
  end

  private

  def messages_to_me
    Message.where(THEM_TO_ME, ids)
  end

  def ids
    { :my_id => @me.id, :their_id => @them.id }
  end
end

2) Conversations 是否需要持久化到数据库中?

如果Message看起来像下面这样,那么您可以Conversation通过接收一条消息然后遵循先前的消息链来初始化 a。

class Message < ActiveRecord::Base
  belongs_to :sender, class_name: 'User'
  belongs_to :recipient, class_name: 'User'
  belongs_to :previous_message, class_name: 'Message'
end

class Conversation
  def initialize(message)
    @message = message
  end

  def messages
    //use @message to follow the chain of messages
  end
end
于 2013-03-14T14:43:10.220 回答