Retactoring advanced has_many示例

时间:2010-03-13 11:46:49

标签: ruby-on-rails

我的用户模型对于相同的消息模型有三个关系,并使用原始SQL:/是否有更好的rails方式来实现相同的结果?

是否可以动态更改外键?例如User.messages.sent(foreign key = author_id)和User.messages.received(外键=收件人)我一直试图将一些逻辑移动到消息模型的范围中,但是user.id不能从消息模型......

有什么想法吗?

表格布局:

  create_table "messages", :force => true do |t|
    t.string   "subject"
    t.text     "body"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "author_id"
    t.integer  "recipient_id"
    t.boolean  "author_deleted",    :default => false
    t.boolean  "recipient_deleted", :default => false
  end

这是我与用户模型的关系:

  has_many :messages_received, :foreign_key => "recipient_id", :class_name => "Message", :conditions => ['recipient_deleted = ?', false]
  has_many :messages_sent, :foreign_key => "author_id", :class_name => "Message", :conditions => ['author_deleted = ?', false]
  has_many :messages_deleted, :class_name => "Message", :finder_sql => 'SELECT * FROM Messages WHERE
                                                                        author_id = #{self.id} AND author_deleted = true OR
                                                                        recipient_id = #{self.id} AND recipient_deleted = true'

祝你好运。 AsbjørnMorell

1 个答案:

答案 0 :(得分:3)

是的,使用named_scope对已删除和未删除的邮件进行排序。

class User < ActiveRecord::Base
  has_many :messages_received, :foreign_key  => 'recipient_id'
  has_many :messages_sent, :foreign_key => 'author_id'
end

class Messages < ActiveRecord::Base
  named_scope :deleted, :conditions => 'author_deleted = TRUE OR recipient_deleted = TRUE' 
  named_scope :not_deleted, :conditions => 'author_deleted = FALSE OR recipient_deleted = FALSE'
end

# Example user
user = User.first
user.messages_received.deleted
user.messages_received.not_deleted
user.messages_sent.deleted
user.messages_sent.not_deleted

或者,您可以更进一步,使用user_id作为外键并指定消息类型来简化关联。

create_table "messages", :force => true do |t|
  t.string   "subject"
  t.text     "body"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.string   "message_type"
  t.integer  "user_id"
  t.boolean  "deleted", :default => false
end

class User < ActiveRecord::Base
  has_many :messages
end

class Messages < ActiveRecord::Base
  MESSAGE_TYPES = %w[Recipient Author]

  belongs_to :user

  named_scope :recipient, :conditions => {:message_type => 'Recipient'}
  named_scope :author, :conditions => {:message_type => 'Author'}
  named_scope :deleted, :conditions => {:deleted => true}
  named_scope :not_deleted, :conditions => {:deleted => false}

  # Convenience class methods
  def self.sent
    author.not_deleted
  end

  def self.received
    recipient.not_deleted
  end
end

# Example usage
user = User.first
user.messages.sent
user.messages.received
user.messages.deleted

这种方法很有优势,因为:

  1. 少一栏。
  2. 扩的。将来添加其他消息类型是微不足道的(例如:草稿)。