开发者

per user lookups

I'm working on rewriting a large, horribly written php app in rails. We've been running the app in production for several years now and have a good sense now of what it actually needs to do, so I'm looking to start clean and finally get out a solid codebase to support our app.

One thing I'm trying to figure out is how to handle some functionality we have on a lot of our models. The app is a multi-company web application, and each company (and all users) that use the app have a lot of preferences and custom lookups. Preferences are easy, I plan to just set up a preferences model for users and companies and make those essentially key/value tables. I'm struggling a bit more with our lookup models though. Take for example, status. In a typical app you'd have a status table and be done with it. In our case, status is something that can vary depending on the company of the logged in user.

In the current app, this is implemented rather poorly I think. We essentially have a Status table and model, with a company_id column. We provide a set of default statuses, with company_id = -1. Then, if a company overrides these, we save entries to the table with their company_id. In the app, we fetch these via stored procedur开发者_开发知识库es, which we basically pass in a company_id and it returns either the default entries or the company specific entries.

I'm not a fan of this, mostly because it makes it difficult to easily access the data. Specifically, having defaults and company specific options in a table means that you can't do a simple query to get a list of statuses, it either has to be 2 queries (for company_id and then if no results, for -1) or a complex query/procedure doing a count and if statement in sql. On the plus side though, it does allow for easy relations, since other objects can reference a status_id and get whatever status is in the table.

We have this functionality on probably a dozen different models, so I'm trying to come up with a good model for this that can be easily implemented on any model.

Does anyone have any suggestions on a better way this could be implemented?


One possibility would be to simply implement status as a method of the User model. For example:

class User < ActiveRecord::Base
  belongs_to :company

  # users table has a status column
  def status
    read_attribute(:status) || company.default_status
  end
end

Now the user can have a status set, or the status can be NULL. If the status is NULL, then read_attribute(:status) returns nil, and instead we return company.default_status.

If you need to get more complex than this and possibly have multiple statuses per user, you can do a similar trick on the Status model, where you override the reader for the relevant value column and provide a fallback case if the value is NULL.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜