Rails association with almost all other models -



Rails association with almost all other models -

i'm looking suggestions on how deal "regions" in system. other models in scheme (news, events, projects, , others) need have part can sorted on. far, i've considered part model has_many :through on regionlink table. i've never had model joined many others , wonder if route has negatives. i've considered using acts_as_taggable_on gem , tag regions models. seems ok i'll have write more cleanup type code handle client renaming or removing region.

whatever take need handle renaming and, more importantly, deleting regions. if part gets deleted give user selection on part replace association.

any advice on handling appreciated.

if each news, event, etc. belong 1 region, tags don't seem natural fit imo. leaves 2 options:

add region_id field each model

this simplest, has drawback not able @ "regioned" items @ 1 time - you'll have query news, events, etc. tables separately (or utilize union, activerecord doesn't support).

use regionlink model polymorphic associations

this more complicated, , in fact similar how acts_as_taggable_on works. @ rails docs on *belongs_to* fuller description of polymorphic relationships if unfamiliar

class part < activerecord::base has_many :region_links has_many :things, :through => :region_links end # table have region_id, thing_id , thing_type class regionlink < activerecord::base belongs_to :region belongs_to :thing, :polymorphic => true end class event < activerecord::base has_one :region_link, :as => :thing has_one :region, :through => :region_link end # "things" (events, projects, etc.) part #1 things = region.find(1).things

renaming quite simple - rename region. deleting/reassigning regions simple - delete regionlink record, or replace it's region_id.

if find duplicating lot of region-related code in event, etc. models, may want set module in lib or app/models:

module regioned def self.inluded(base) base.class_eval has_one :region_link, :as => :thing has_one :region, :through => :region_link ... end end end class event < activerecord::base include regioned end class project < activerecord::base include regioned end

ruby-on-rails ruby-on-rails-3.1 associations

Comments

Popular posts from this blog

How do I check if an insert was successful with MySQLdb in Python? -

delphi - blogger via idHTTP : error 400 bad request -

postgresql - ERROR: operator is not unique: unknown + unknown -