我想在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中使用它们。我该如何解决这个问题?
答案 0 :(得分: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])
如果此用户是UserForAdmin
,您将收到类UserForAdmin
的对象。如果它只是一个用户,您将收到类User