質問

I have model User and model Recruiter. Currently, these are two separate tables, but I want to make them one.

Current:

  • User: id, username, password, name
  • Recruiter: id, user_id

Ideal:

  • User: id, username, password, role (recruiter, admin)

I understand the basics of STI. What I'm wondering is, when I perform methods on the new Recruiter controller (that inherits from User) how do I make sure all my methods are calling on users that are only a recruiter? Thus, queries along the lines of... SELECT * FROM users WHERE role = 'recruiter' for everything.

役に立ちましたか?

解決

That is something rails takes care of for you, out of the box. You do not have to manually query on a particular type of user, just query on the right model.

I must also mention that by default rails assumes that your sti_column is called type, but can be overridden to role easily.

他のヒント

Let's admit you have your 2 classes:

class User < ActiveRecord::Base
end

class Recruiter < User
end

Rails will automagically add a type column in the users table so that in your controller, if you do something like this:

class RecruitersController < ApplicationController
  def index
    @recruiters = Recruiter.all
  end
end

Rails will automatically fetch the records with type = 'Recruiter' and you don't even have to set this manually. If you do:

Recruiter.new(name: 'John').save

A new User will be created in database with the field type set to 'Recruiter'.

you would define your models something like this:

 class User < ActiveRecord::Base
   ...
 end

 class Recruiter < User
 ...
   def initialize
     # ... special initialization for recruiters / you could put it here
     super
   end
 ...
 end

and to create a new recruiter, you would do this:

 Recruiter.create(:name => "John Smith")

and because of the type attribute in the STI user table (set to 'Recruiter'), the record will be for a recruiter.

You could put the special initialization for the STI models either in the model's initializer, or in a before filter with a if-cascade checking the type. An initializer is probably much cleaner.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top