Usually there are a lot of models in a Ruby on Rails project, so:
Is it a good practice to namespace them (in modules/folders)? What are the downsides?
EG:
Shop
category.rb
details.rb
Products
category.rb
base.rb
etc
(instead of ShopCategory, to have Shop::Category?)
Should also the controllers be namespaced in the same manner?
I've recently found this post but back from 2007 by Pratik Naik. Says there namespace in models doesn't really resemble databases. Uses something like below. Even there's a quote from DHH too.
Rails::Initializer.run do |config|
# Your existing stuff
config.load_paths << "#{RAILS_ROOT}/app/models/pets"
end
http://m.onkey.org/2007/12/9/namespaced-models
p/s: I don't know whether the post is still relevant or not, just something I found recently when I wanted namespaces in my models.
I'm doing that a lot.
So yes I think that's something you should do.
It'll be be a lot easier for you to view models if you have them subdivided in subdirectories instead of having them all in the same one.
The same recommendation is also valid for your controllers and your views.
I recommend using single table inheritance for your category model. For example:
Category < ActiveRecord::Base end
ShopCategory < Category end
ProductCategory < Category end
Shop < ActiveRecord::Base
belongs_to :shop_category
end
Product < ActiveRecord::Base
belongs_to :product_category
end
This will encapsulate commonly used category behaviour and attributes into a single model and could allow you to reuse a lot of code and have a single controller. Using namespacing only makes sense to me when the underlying classes have some sort of data/functionality in common. (example: acts_as_versioned creates a Version class namespaced under the model)
Related
I would like to convert all my models in a rails app to use uuid as id and maybe if I need, add some fields that will be common to all my models. To do this I am thinking of, instead of doing this:
class MyModel < ActiveRecord::Base
end
doing this
class CommonUUIDModel < ActiveRecord::Base
some_uuid_related_information
end
class MyModel < CommonUUIDModel
end
my questions are:
How can I achieve this (what should be in the place of some_uuid_related_information and is this a good practice for Rails applications?
Prefer extension (mixing in modules) to inheritance (subclasses).
In other words, make a module that alters the models in a uniform way and include that module in all classes that use it.
This is especially true of ActiveRecord-backed models, since subclassing often signals STI (single table inheritance)
I have an application which defines some models. I want to extend the functionality of some models(eg. adding methods,adding associations) from application to my engine.
I tried adding a model in the engine with the same name as my application's model and Rails will automatically merge them, however it doesn't work.
eg:
(Application's model)
class Article < ActiveRecord:Base
def from_application
puts "application"
end
end
(Inside my Engine)
module MyEngine
class Article < ::Article
has_many :metrics, :class_name => 'Metric'
end
end
has_many association is not getting applied to my Articles model when I try to access #articles.metrics. Any ideas ?
You have the right idea and are close. But your implementation is a little off.
Generally, your engine should have no knowledge of your host app. That way, your engine and the host app(s) stay loosely coupled. So, classes in your engine should not inherit from classes in your host app. (BTW, your approach doesn't work, I believe, because of the way ruby does constant lookups, but that's a different discussion.)
Instead, use the included hook. In the host app, you do something like:
class Article < ActiveRecord:Base
include FooEngine::BarModule
def from_application
puts "application"
end
end
And inside the engine:
module FooEngine
module BarModule
def self.included(base)
base.class_eval do
has_many :metrics, :class_name => 'Metric'
end
end
end
end
When the ruby interpreter goes to include FooEngine::BarModule in Article, it will look for and run (if found) the self.included method in FooEngine::BarModule, passing in the Articleclass as base.
You then call class_eval on the base (Article) which re-opens the Article class so that you can add methods or whatever monkey business you're up to (define new methods in situ, include or extend other modules, etc.).
In your example, you call the has_many method, which will create the various association methods provided by has_many.
If (a) you're going to add a lot of metrics-related functionality through your engine, (b) you want to have lots of classes make use of the metrics-related functionality, and (c) you want some of the functionality to vary from class-to-class (where included), you might consider creating an acts_as_having_metrics (or similar). Once you head down this path, it's a whole new world of wondrous metaprogramming.
Best of luck.
Do you have your metrics model have a belongs_to association with Articles.
You might want to give the other side of the association, Metrics a belongs_to Articles to have this work properly. Also, make sure to have a migration to hold articles_id on the metrics table. Everything should work fine.
I'm creating models that are specific to another model (which will ultimately be embedded in the parent model using Mongoid). Now I'm just stuck with trying to figure out how to name them. I've seen it done both ways, so I don't know what to do:
Singular:
models/
post.rb
post/
comment.rb
comment/
happy_comment.rb
class Post
class Post::Comment
class Post::Comment::HappyComment < Post::Comment
Plural:
models/
post.rb
posts/
comment.rb
comments/
happy_comment.rb
class Post
class Posts::Comment
class Posts::Comments::HappyComment < Posts::Comment
The benefit to the later is that there can be Posts and Comments modules for wrapping around each child model:
module Posts
module Comments
class HappyComment < Comment
What is the correct way to namespace these child models?
There is no generally accepted convention for this and you can use both, depending on what you find better. From technical point of view, Rails will not behave differently in the two situations.
P.S. Are you going to also have other models, named Post, Comment etc.? If not, than maybe the best approach is to just have each model at the top level of your models/ folder.
Short version: Where should I store environment-specific IDs? ENV['some-variable']? Somewhere else?
Long version:
Let's say I have a model called Books and a book has a Category. (For the sake of this question, let's say a book only has one category.)
class Book < ActiveRecord::Base
belongs_to :category
end
class Category < ActiveRecord::Base
has_many :books
end
Now let's say one category is called 'erotica.' And I want to suppress erotica books in my type ahead. That seems straight forward. But in production and in development 'erotica' has a different ID. I don't want my code to be ID dependent. I don't want it to be string dependent (in case 'erotica' is renamed pr0n or whatever).
I think I should have something like
def suppress_method
suppress_category_id = look_up_suppression_id
...
end
but where should 'look up' look?
Thanks!
Taking this approach will be brittle, what if you want to suppress multiple categories? Erotica and Politics? The best design here is for you to actually add 'suppressed' as a boolean to category in a migration, and maintain that in your application's administration interface. After you've done that you can add a named scope like:
class Category < ActiveRecord::Base
named_scope :not_suppressed, :conditions=>{:suppressed=>false}
# or for rails 3
scope :not_suppressed, where(:suppressed=>false)
end
Then just update your type ahead code to do:
Category.not_suppressed.find ...
Rather than
Category.find
I am working on a very large Rails application. We initially did not use much inheritance, but we have had some eye opening experiences from a consultant and are looking to refactor some of our models.
We have the following pattern a lot in our application:
class Project < ActiveRecord::Base
has_many :graph_settings
end
class GraphType < ActiveRecord::Base
has_many :graph_settings
#graph type specific settings (units, labels, etc) stored in DB and very infrequently updated.
end
class GraphSetting < ActiveRecord::Base
belongs_to :graph_type
belongs_to :project
# Project implementation of graph type specific settings (y_min, y_max) also stored in db.
end
This also results in a ton of conditionals in views, helpers and in the GraphSetting model itself. None of this is good.
A simple refactor where we get rid of GraphType in favor of using a structure more like this:
class Graph < ActiveRecord::Base
belongs_to :project
# Generic methods and settings
end
class SpecificGraph < Graph
# Default methods and settings hard coded
# Project implementation specific details stored in db.
end
Now this makes perfect sense to me, eases testing, removes conditionals, and makes later internationalization easier. However we only have 15 to 30 graphs.
We have a very similar model (to complicated to use as an example) with close to probably 100 different 'types', and could potentially double that. They would all have relationships and methods they inheritated, some would need to override more methods then others. It seems like the perfect use, but that many just seems like a lot.
Is 200 STI classes to many? Is there another pattern we should look at?
Thanks for any wisdom and I will answer any questions.
If the differences are just in the behavior of the class, then I assume it shouldn't be a problem, and this is a good candidate for STI. (Mind you, I've never tried this with so many subclasses.)
But, if your 200 STI classes each have some unique attributes, you would need a lot of extra database columns in the master table which would be NULL, 99.5% of the time. This could be very inefficient.
To create something like "multiple table inheritance", what I've done before with success was to use a little metaprogramming to associate other tables for the details unique to each class:
class SpecificGraph < Graph
include SpecificGraphDetail::MTI
end
class SpecificGraphDetail < ActiveRecord::Base
module MTI
def self.included(base)
base.class_eval do
has_one :specific_graph_detail, :foreign_key => 'graph_id', :dependent => :destroy
delegate :extra_column, :extra_column=, :to => :specific_graph_detail
end
end
end
end
The delegation means you can access the associated detail fields as if they were directly on the model instead of going through the specific_graph_detail association, and for all intents and purposes it "looks" like these are just extra columns.
You have to trade off the situations where you need to join these extra detail tables against just having the extra columns in the master table. That will decide whether to use STI or a solution using associated tables, such as my solution above.