Rails STI - same records for sub-sub-class - ruby-on-rails

Models:
class User < ActiveRecord::Base
end
class Admin < User
end
class SpecialAdmin < Admin
end
I would like SpecialAdmin to have the same records/dataset as Admin model. Each SpecialAdmin record could for example have "Admin" in its type column when edited/created - any other similar solution would be fine too.
I tried this
self.inheritance_column :nil # Didnt work because it fetches all records in the table
...becomes method # Didnt get this to work either
Thanks for any input!

Related

superclass mismatch for class User - inheriting from ActiveRecord::Base

I am trying to figure out my superclass mismatch error. All the posts I've read about this describe the problem as being that User is defined twice as a class in my application.
In my case, it isn't defined twice. I have a services folder and within that I have a user folder (for user service classes). In that user folder, I have a file called organisation_mapper_service.rb, with:
class User < ActiveRecord::Base
class OrganisationMapperService
def self.call(user: u)
new(user: user).call
end
def initialize(user: u)
self.user = user
end
def call
if matching_organisation.present?
# user.organisation_request.new(organisation_id: matching_organisation.id)
# user.update_attributes!(organisation_id: matching_organisation.id)
else
#SystemMailer.unmatched_organisation(user: user).deliver_now
end
end
private
attr_accessor :user
def matching_organisation
User::OrganisationMapperService.new(user).matching_organisation
end
end
end
Separate to that, I have my user model which defines user as:
class User < ApplicationRecord
I thought it should be fine to define the service class in the way I have because it inherits from ActiveRecord::Base rather than ApplicationRecord.
Can anyone see what I've done wrong here? Where else could I look for a second definition of User?
TAKING SERGIO'S SUGGESTION
I change the user organisation mapper service to open as follows:
class User::OrganisationMapperService < ActiveRecord::Base
But that then gives an error with my Users::OrgRequestsController which has new defined as follows:
def new
#all_organisations = Organisation.select(:title, :id).map { |org| [org.title, org.id] }
#org_request = OrgRequest.new#form(OrganisationRequest::Create)
matched_organisation = User::OrganisationMapperService.new(current_user).matching_organisation
#org_request.organisation_id = matched_organisation.try(:id)
end
the error message then says:
PG::UndefinedTable at /users/4/org_requests/new
ERROR: relation "user_organisation_mapper_services" does not exist
LINE 8: WHERE a.attrelid = '"user_organisation_mapper...
**TAKING SERGIO'S SUGGESTION (exactly) **
I change my service class to:
class User::OrganisationMapperService
But then I get an error that says:
wrong number of arguments (given 1, expected 0)
That error highlights this line of my service class:
def initialize(user: u)
self.user = user
end
I don't know what to do about that because I clearly have a user if there is an inheritance from user.
Even once you solve all your other issues, you actually have an infinite recursion going on.
User::OrganisationMapperService.call(user: User.first)
Is equivalent to calling:
User::OrganisationMapperService.new(user: User.first).call
Which internally calls matching_organisation, so is sort of equivalent to:
User::OrganisationMapperService.new(user: User.first).matching_organisation
Meanwhile, matching_organisation calls
User::OrganisationMapperService.new(user).matching_organisation
It's just going to go round and round in circles.
The only reason it doesn't is because of the wrong number of arguments (given 1, expected 0) error. This is because it should be User::OrganisationMapperService.new(user: user) rather than User::OrganisationMapperService.new(user) in your matching_organisation method.
Update in response to comment:
From what I understand, the User::OrganisationMapperService is a service class that does the job of finding some Organisation and then performing some sort of work.
The User::OrganisationMapperService#matching_organisation method should actually contain the code that returns the matching organisation for the given user. The implementation will completely depend on how you have structured your database, but I'll give a couple of examples to put you on the right track or give you ideas.
First, Your organisations table may have a user_id column. In this case you could do a simple query on the Organisation model and perform a search using the user's id:
class User::OrganisationMapperService
def matching_organisation
# find the organisation and cache the result
#matching_organisation ||= ::Organisation.where(user_id: user).first
end
end
Alternatively, you may have some sort of join table where there may be multiple Users at an Organisation (just for this example let us call this table 'employments'):
class Employment < ApplicationRecord
belongs_to :user
belongs_to :organisation
end
We can add scopes (this is a must read) to the Organisation model to assist with the query:
class Organisation < ApplicationRecord
has_many :employments
has_many :users, through: :employments
scope :for_user, ->(user) {
# return organisations belonging to this user
joins(:users).merge( Employment.where(user_id: user) )
}
end
Then finally, the OrganisationMapperService#matching_organisation method becomes:
class User::OrganisationMapperService
def matching_organisation
# find the organisation and cache the result
#matching_organisation ||= ::Organisation.for_user(user).first
end
end
You are defining User class with two separate parent classes. Don't do that.
It should be
class User::OrganisationMapperService
This way, your existing User class will be loaded and used, rather than a new one created.
I thought it should be fine to define the service class in the way I have because it inherits from ActiveRecord::Base rather than ApplicationRecord.
The service class in your example doesn't inherit from anything.

Rails 4 - Mapping a model dynamically on two different database tables

I have a multi domain app talking to a legacy database.
In that DB I have two tables with different names, lets call them USER_A and USER_B. Their structure and data types are exactly the same, the only difference is that they get their data from different domains.
Now, I would like to have a single scaffold (model/controller/view) that, depending on the domain, maps to the right DB table.
Domain A would work with a model/controller called User which maps internally to the db table USER_A, and Domain B would work with the same model/controller User but maps to the table USER_B.
I would also like to use resource :user in my routes to access the model the rails way.
So somehow I need to overwrite the model on initialization but I am not quite sure how to go about it.
How would one go about this using Rails ActiveRecord?
I don't have a multitable DB ready to test with, so this is an educated guess at the solution:
# respective models
class User < ActiveRecord::Base
end
class DomainAUser < User
self.table_name = "USER_A"
end
class DomainBUser < User
self.table_name = "USER_B"
end
# controller
def set_user
#user = if request.subdomain(0) == "DomainA"
DomainAUser.find(params[:id])
else
DomainBUser.find(params[:id])
end
end
Edit: Here's an alternative bit of metaprogramming hackery which does the subclass instantization within the parent class itself. Tested and working.
I really wouldn't want to maintain something like this though.
# model
class User < ActiveRecord::Base
def self.for_domain(domain_suffix)
class_eval "class DomainUser < User; self.table_name='user_#{domain_suffix}'; end"
"User::DomainUser".constantize
end
end
# controller
User.for_domain("a").new

Rails model inherit business logic only

In a rails 4 app I have two models with the same schema but different tables. They are FeedEntry and HistoricalFeedEntry. I would like HistoricalFeedEntry to only inherit functionality I add to FeedEntry. The models look like so:
class FeedEntry < ActiveRecord::Base
def self.published_at_cutoff
# date cutoff before which entries are old
Time.now - 1*7*24*60*60
end
end
class HistoricalFeedEntry < FeedEntry
end
When I enter the rails console and do HistoricalFeedEntry.all I get all the results from the FeedEntry table. What I would like is to only inherit published_at_cutoff (and other methods defined by me). Thanks.
You can use a mix-in for such a thing. Create a module which contains the business logic, class methods and instance methods. And "include" it in each of the models. Something like below:
class FeedEntry < ActiveRecord::Base
include FeedEntryBusinessLogic
end
module FeedEntryBusinessLogic
def self.published_at_cutoff
# date cutoff before which entries are old
Time.now - 1*7*24*60*60
end
end
class HistoricalFeedEntry < ActiveRecord::Base
include FeedEntryBusinessLogic
end
Because you are using Rails 4, you can use Concerns ( which are similar ). Read:
https://signalvnoise.com/posts/3372-put-chubby-models-on-a-diet-with-concerns

relation "admin_keywords" does not exist`

I want to have scaffold actions for Keywords table as admin. This code begins to work after I restart the server and Remove Admin:: from /app/models/admin/keyword.rb, then refresh website, get error and adding Admin:: to model again. From that moment everything works fine. But after server Starts, I got this: (Rails 4)
PG::UndefinedTable: ERROR: relation "admin_keywords" does not exist
/app/controllers/admin/keywords_controller.rb source:
class Admin::KeywordsController < ApplicationController
def index
#keywords = Admin::Keyword.all
end
end
/app/models/admin/keyword.rb source:
class Admin::Keyword < ActiveRecord::Base
end
going to url:
http://localhost:3000/admin/keywords
routes.rb:
namespace :admin do
resources :keywords
end
How to fix this error?
If you add namespace to your models, database table should contain this namespace too. For example model Admin::Keyword is related with admin_keywords table.
You can override model's table defining self.table_name='your_table_name' method in model.
class Admin::Keyword < ActiveRecord::Base
self.table_name = 'your_table_name'
end

How do I extract this so it can be reused in other parts of my app?

I have this method in my book model but now I realize I need this in a category model as well:
def proper_user?(logged_in_user)
return false unless logged_in_user.is_a? User
user == logged_in_user
end
I now have this method duplicated in the books model and the category model. Both category and books has belongs_to :user and both have the user_id:integer in the table as well. I simply want to extract this somewhere where so I can its DRY.
i tried to put the method in application_controller.rb but it says undefined method `proper_user?' for #
Thanks
Jeff
I think you'd want to be able to call this method like this:
book.proper_user?(current_user)
So it would work best to define it in each model rather then in User. This is best done by mixing in a module with the method:
module UserMethods
def proper_user?(logged_in_user)
# ... etc ...
end
end
and including it in each model:
class Book < AR::Base
include UserMethods
class Category < AR::Base
include UserMethods
The module can go in a source file in config/initializers, or you can put it elsewhere and change config.autoload_paths in config/environment.rb to point to the location.
Since it is related to the User model, why not put it there?

Resources