0

我想在 Rails 中做 STI。

class AbstractUser < ActiveRecord::Base
  self.table_name = 'users'

  belongs_to :organization, :inverse_of => :users

  # reporter user
  has_many  :requests, :dependent => :destroy

  # startup user
  has_many  :responses, :dependent => :destroy
  has_many  :startup_requests, :through => :responses, :source => :request

  scope :reporters, where(:type => 'Reporter')
  scope :startup_employees, where(:type => 'Startup')
  scope :on_waitlist, where(:waitlist => true)
  scope :not_on_waitlist, where(:waitlist => false)

end

require 'rfc822'

class User < AbstractUser
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :confirmable

  validates :name, :presence => true
  validates :surname, :presence => true
  validates :title, :presence => true
  validates :password, :presence => true, :length => { :minimum => 8 }
  validates :email, :presence => true, :format => { :with => RFC822::EMAIL_REGEXP_WHOLE }

  attr_accessible :name, :surname, :title, :organization,
                  :email, :password, :fullname
end

require 'rfc822'

class UserForAdmin < AbstractUser
  validates :email, :presence => true, :format => { :with => RFC822::EMAIL_REGEXP_WHOLE }
  validates :organization_id, :presence => true

  attr_accessible :name, :surname, :title, :organization, :email,
                  :password, :fullname, :password_confirmation, :type, 
                  :organization_id, :waitlist, :invitation_token
end

这些范围存在一些问题。

Couldn't find UserForAdmin with id=7 [WHERE "users"."type" IN ('UserForAdmin') AND "users"."waitlist" = 'f']

我还尝试将这些范围放入UserForAdmin而不是AbstractUser获得相同的结果。我(可能)需要范围而不是自定义方法,因为我在 ActiveAdmin 中使用它们。我该如何解决这个问题?

4

1 回答 1

1

如果不想接收所有用户,需要用基类查询。在一个更简单的例子中:

class Animal < ActiveRecord::Base
end

class Dog < Animal
end

class Cat < Animal
end

Dog.create
Cat.create

Animal.all
=> [dog, cat]

Dog.all
=> [dog]

Cat.all
=> [cat]

所以,在你的情况下,你想要:

AbstractUser.not_on_waitlist.find(params[:id])

如果此用户是 aUserForAdmin您将收到 class 的对象UserForAdmin。如果它只是一个用户,你会收到一个类的对象User

于 2013-05-22T14:07:31.810 回答