Forum: Ruby on Rails Active Record design seems awkward and possibly broken

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Graham G. (Guest)
on 2005-11-26 09:17
Hi Guys,

I've been using Rails for the first time and have encountered some
issues that I'm not sure are a result of my inexperience with Rails or a
design oversight.

In my domain model, a School has an Address. In SQL, I've defined a
"schools" table and an "addresses" table, and the "schools" table
defines a column called "address_id" that refers to a row in the
"addresses" table.

When I model this using ActiveRecord, it seems that I'm meant to put a
line into the School model that looks like this:

class School < ActiveRecord::Base
  belongs_to :address
end

and a line into the Address model that looks like this:

class Address < ActiveRecord::Base
  has_many :schools
end

First of all, this seems unintuitive, since you don't naturally think of
a School "belonging" to an Address, but the user documentation says that
the "belongs_to" clause should reside in the class whose table contains
the foreign key (in this case, "address_id").

Second, when a School is destroyed I want its corresponding Address to
be automatically destroyed but I can't do this using the above
declaration because the :dependent mechanism attaches to the :has_many
clause. In other words, I can arrange for a School to be destroyed when
its Address is destroyed, but not the other way around!

Am I missing something here, or is this a Rails design problem? If it's
the latter, I highly recommend that it's fixed before Rails goes to
version 1.0.

Regards,
Graham
petermichaux (Guest)
on 2005-11-26 09:34
(Received via mailing list)
If more than one school can belong to an address then do you really want
to
delete the address when you delete a school? Perhaps you really want
"has
one :school" in your school model. If so...

I haven't tried this code and I'm no expert...

class School < ActiveRecord::Base
>   belongs_to :address


# use a callback to delete the address after the school has been
successfully deleted.
def after_destroy
  Address.delete(address.id)
end

end


Rails book pages 224 & 275

- Peter
Graham G. (Guest)
on 2005-11-26 09:44
Hi Peter,

I think you're right that the School can use "has_one" to ensure a 1-1
mapping between School and Address, but the School still has to be the
one with the "belongs_to" statement since it has the foreign key to the
address. This means that the "ownership" is the wrong way around, and I
still can't arrange for the Address to be destroyed when the School is
destroyed.

The example in the Ruby on Rails book by Dave T. uses an example
where an "Invoice" belongs to an "Order". This is appropriate use of the
word "belongs_to", but it seems that maybe the ActiveRecord design was
built around examples like that one and does not take into account other
(quite common) situations like my School example where the "ownership"
is in fact in the opposite direction.

Also, you're right, I can work around this issue by using callbacks, but
the whole point of frameworks like Rails is to codify common design
patterns so you don't have to do this kind of work manually.
sanfordsv (Guest)
on 2005-11-26 11:35
(Received via mailing list)
If 'address' is just an attribute of 'School' there's no need to store
an explicit pointer to the address record in the 'School' record.
Typically you'd store the school_id in the Address record and do the
lookup from that direction (leave the back-association in the dependent
info, not the primary info).

Try using 'has_one :address' in the School model and 'belongs_to:' in
the Address.

In the School table you can leave out the address_id, just add a
'school_id' in the Address record.

':dependent' should work fine then.
beattie.mark (Guest)
on 2005-11-26 11:51
(Received via mailing list)
On 11/26/05, Sanford SV <removed_email_address@domain.invalid> wrote:
> Try using 'has_one :address' in the School model and 'belongs_to:' in
> the Address.
>
> In the School table you can leave out the address_id, just add a
> 'school_id' in the Address record.
>
> ':dependent' should work fine then.

I'd agree with Sanford, School :has_one Address makes more sense, but
if it's a one-to-one relationship why couldn't you just have the
school's address in the schools table?

I'd be quite interested in what project you're working on actually.
I'm currently rebuilding a PHP based school management system in Rails
and could offer some insights into the DB design. Rails is a dream
until you run into 3-way bridge tables for example.

Mark B.
Easy Schedule Management
http://easy-online-schedule.com
Graham G. (Guest)
on 2005-11-26 11:55
Your approach would work in this particular case, but it's very likely
that other entities will also have addresses. Rather than hardwiring a
back reference from the Address to a School, it seems like better
database design practice for higher-level tables to refer to lower-level
tables rather than the other way around.

In other words, I don't want to warp my database structure to fit the
ActiveRecord framework, I want ActiveRecord to support good relational
database design.

Regards,
Graham
Graham G. <> (Guest)
on 2005-11-26 11:57
beattie.mark wrote:
> On 11/26/05, Sanford SV <removed_email_address@domain.invalid> wrote:
>> Try using 'has_one :address' in the School model and 'belongs_to:' in
>> the Address.
>>
>> In the School table you can leave out the address_id, just add a
>> 'school_id' in the Address record.
>>
>> ':dependent' should work fine then.
>
> I'd agree with Sanford, School :has_one Address makes more sense, but
> if it's a one-to-one relationship why couldn't you just have the
> school's address in the schools table?
>
> I'd be quite interested in what project you're working on actually.
> I'm currently rebuilding a PHP based school management system in Rails
> and could offer some insights into the DB design. Rails is a dream
> until you run into 3-way bridge tables for example.
>
> Mark B.
> Easy Schedule Management
> http://easy-online-schedule.com

Hi Mark,

You *could* embed the address into the school table, but since addresses
are commonly occuring entities (students can have an address as well for
example), it makes more sense to have a separate table for addresses.

I'm working on an online education system that was prototyped in PHP and
is now being ported to Rails. It focuses on the teaching/learning part
of the equation rather than the school management stuff.

Regards,
Graham
brucebalmer (Guest)
on 2005-11-26 14:21
(Received via mailing list)
Would it be reasonable to change which table has the foreign key in
it? Would that make the belongs_to more intuitive?

Could you reasonably combine school and address into one table
(assuming a one to one link between the two)? Is a 1:1 link not
generally a sign that, perhaps the two tables should really be one?

I know there are reasons to split a table into two 1:1 tables - just
a suggestion.

bruce
tomasj (Guest)
on 2005-11-26 15:33
(Received via mailing list)
> The example in the Ruby on Rails book by Dave T. uses an example
> where an "Invoice" belongs to an "Order". This is appropriate use of the
> word "belongs_to", but it seems that maybe the ActiveRecord design was
> built around examples like that one and does not take into account other
> (quite common) situations like my School example where the "ownership"
> is in fact in the opposite direction.

Absolutely. So your only problem is the choice of the word "belongs
to" to describe the functionality, not the functionality itself?
Perhaps you could just ignore this very small problem and it will go
away?

Since people seem to run into this "problem" all the time, maybe the
belongs_to method should be aliased to some other method with a name
that infers the opposite ownership.

Regards,
Tomas J.
morg (Guest)
on 2005-11-26 16:05
(Received via mailing list)
Do it the other way

Addresses belongs_to :school and have a school_id
Schools then has_one :address
christopher.k.hall (Guest)
on 2005-11-26 16:33
(Received via mailing list)
if you don't need to normalize, don't.  there's such a thing as over
normalizing.

there's nothing wrong with putting the address in the schools table.
now it
may make sense to normalize a students table, where it's quite possible
that
a student could have more than one address (say mom/dad live at separate
addresses, etc).  in this case, yes, definitely normalize the address
out to
a separate table.  but for the case of a school which has one and only
one
address, it's perfectly fine to leave the address in the school table.
that
would not be a case of bad design.
robby.lists (Guest)
on 2005-11-26 17:50
(Received via mailing list)
On Sat, 2005-11-26 at 08:17 +0100, Graham G. wrote:
>
>   has_many :schools
> clause. In other words, I can arrange for a School to be destroyed when
> its Address is destroyed, but not the other way around!
>
> Am I missing something here, or is this a Rails design problem? If it's
> the latter, I highly recommend that it's fixed before Rails goes to
> version 1.0.

Try this:

http://www.robbyonrails.com/articles/2005/10/19/ne...

RubyURL: http://rubyurl.com/bE4

-Robby

--
/******************************************************
* Robby R., Founder.Developer.Geek
* PLANET ARGON, Rails Development, Consulting & Hosting
* Portland, Oregon  | p: 503.351.4730 | f: 815.642.4068
* www.planetargon.com | www.robbyonrails.com
* Programming Rails   | www.programmingrails.com
*******************************************************/
petermichaux (Guest)
on 2005-11-26 20:15
(Received via mailing list)
With the "belongs_to" and "has_many" relationship the way you have it
allows
for several schools to have one address. If you reverse it then a school
could have multiple addresses. you could use has and belongs to many for
both ways. This is a design choice.

Hi Peter,
>
> I think you're right that the School can use "has_one" to ensure a 1-1
> mapping between School and Address, but the School still has to be the
> one with the "belongs_to" statement since it has the foreign key to the
> address. This means that the "ownership" is the wrong way around, and I
> still can't arrange for the Address to be destroyed when the School is
> destroyed.


I don't find the belongs_to statement so offensive but if it is
one-to-one
then the foreign key can be moved to the addresses table.


> The example in the Ruby on Rails book by Dave T. uses an example
> where an "Invoice" belongs to an "Order". This is appropriate use of the
> word "belongs_to", but it seems that maybe the ActiveRecord design was
> built around examples like that one and does not take into account other
> (quite common) situations like my School example where the "ownership"
> is in fact in the opposite direction.


This is a guess but I think the :dependent => true mirrors the SQL
"cascade
on delete". Since there isn't something in SQL that can go in the other
table to reverse the "cascade" (like you want) then there isn't
something in
active record that you want. I think it is because of the multiple
schools/one address type of issue. So you use the magic of callbacks....

Also, you're right, I can work around this issue by using callbacks, but
> the whole point of frameworks like Rails is to codify common design
> patterns so you don't have to do this kind of work manually.
>

I don't think a callback is a work around. It is just the way it is
done.
Callbacks offer more flexibility. If you keep your current has_many
arrangement then the after_destroy call back could delete the address if
the
school being deleted was the last one to have that address.

- Peter
Graham G. <> <graham.glas (Guest)
on 2005-11-26 22:27
Hi Guys,

I really appreciate all the comments here! Although there are several
work-arounds for my specific case suggested, it still seems that
ActiveRecord in its current form does not support a very basic design
pattern that would commonly occur in good data database design.

In my case, the suggestions were:

- embed the address information into the school table,
  thereby avoiding the issue entirely
- embed a school_id into the address table

Both would work in my specific application as it stands right now, but
that is just skirting the issue rather than recognizing the underlying
problem and dealing with it.

For example, if I want to keep a separate addresses table so that, say,
both schools and students could maintain addresses using the same
address schema, then neither of these suggestions works. I guess I could
keep an untyped "owner_id" in the address that refers back to an untyped
foreign key of whoever owns the address, but that seems gross. It seems
more natural for the owner of the address to refer to the address. So
I'd have an "address_id" in the "schools" table and an "address_id" in
the students table.

When I delete a school, I expect its address to be deleted if I indicate
a dependency. That's simple for a framework to do; just use the foreign
key to delete the child.

I like Rails a lot, and one of its strengths is its ability to support
applications naturally and powerfully. Not being able to support the
straightforward table design I outlined above seems to be a weakness in
ActiveRecord that could probably be fixed pretty easily.

Regards,
Graham
petermichaux (Guest)
on 2005-11-26 23:37
(Received via mailing list)
I think active record can do what you want. Untested code but I've done
something just like this attaching images to multiple tables.

TABLES

schools
 id

students
 id

addresses
  owner_class varchar
  owner_id

MODELS

class Student < ActiveRecord::Base
  has_one :address, :foreign_key => 'owner_id', :conditions =>
"owner_class
= #{self.to_s}", :dependent => true

end

class Student < ActiveRecord::Base
  has_one :address, :foreign_key => 'owner_id', :conditions =>
"owner_class
= #{self.to_s}", :dependent => true

end

class address < ActiveRecord::Base
  # as far as I know address cannot belong_to anything because the
referenced table is variable.
  # if someone knows how to do this please post it.
end

- Peter
dom (Guest)
on 2005-11-27 01:50
(Received via mailing list)
On Saturday 26 November 2005 21:06, Peter M. wrote:
>
> end
>   # if someone knows how to do this please post it.
> end

Why not use inheritance to resolve this? Assuming that I understand
the problem correctly. Have a StudentAddress and SchoolAddress which
inherit the Address but are linked to the appropriate tables, or am
I missing something?

> - Peter
>

Cheers,
Si W. (Guest)
on 2005-12-20 05:20
Graham G. <removed_email_address@domain.invalid> <graham.glas wrote:
> Hi Guys,
>
>
> In my case, the suggestions were:
>
> - embed the address information into the school table,
>   thereby avoiding the issue entirely
> - embed a school_id into the address table
>
> Both would work in my specific application as it stands right now, but
> that is just skirting the issue rather than recognizing the underlying
> problem and dealing with it.
>
>

I have to say that I agree very much with this.  What about something
that would have a language attribute, so that you could choose English,
Spanish, etc

table thingy
id, name, language_id

table language
id, lang

Now, that seems to me to be the natural way to accomplish this.  It
lends itself well to creating a pulldown of Language.find(:all).map {|l|
[l.name, l.id]}

It seems counter-intuitive to reverse this logic and attach the thingy
to the language table by creating a thingy_id...
Eero S. (Guest)
on 2005-12-20 05:41
petermichaux wrote:
> I think active record can do what you want. Untested code but I've done
> something just like this attaching images to multiple tables.
>
> TABLES
>
> schools
>  id
>
> students
>  id
>
> addresses
>   owner_class varchar
>   owner_id

This would probably work better as a join table
but those are mainly useful when an entity may
have multiple addresses (which, I suppose, is
possible) :)

> - Peter


E
Eero S. (Guest)
on 2005-12-20 05:55
Graham G. <removed_email_address@domain.invalid> <graham.glas wrote:
> Hi Guys,
>
> I really appreciate all the comments here! Although there are several
> work-arounds for my specific case suggested, it still seems that
> ActiveRecord in its current form does not support a very basic design
> pattern that would commonly occur in good data database design.

Well, it is not so much that it is not supported
than that the naming convention is somewhat awkward
--which I certainly understand: belongs_to and has_one
are precisely inverted in my opinion as well :)

> In my case, the suggestions were:
>
> - embed the address information into the school table,
>   thereby avoiding the issue entirely
> - embed a school_id into the address table
>
> Both would work in my specific application as it stands right now, but
> that is just skirting the issue rather than recognizing the underlying
> problem and dealing with it.
>
> For example, if I want to keep a separate addresses table so that, say,
> both schools and students could maintain addresses using the same
> address schema, then neither of these suggestions works. I guess I could
> keep an untyped "owner_id" ...

An alternative would be to use a join table though
I do not feel this is correct, either, unless you
allow entities to have multiple addresses which is
certainly feasible.

> When I delete a school, I expect its address to be deleted if I indicate
> a dependency. That's simple for a framework to do; just use the foreign
> key to delete the child.

You can either have this be the responsibility of
the database or program logic (which I favour).
Choosing the latter, you would simply hook into
the event of a School being destroyed and issue
a destroy on the address as well. The former you
can handle at the DB level.

> Regards,
> Graham


E
Mark. (Guest)
on 2006-12-02 17:29
> An alternative would be to use a join table though
> I do not feel this is correct, either, unless you
> allow entities to have multiple addresses which is
> certainly feasible.
>
The join table probly reflects the complexity of real life better as
students will have many adresses and one address may have many students.
Even a school could have several addresses. Eg a school could be moving
bewen two sites and have boath addreses valid.

Many (moast?)things tern out to be many to many relationaips in the
moast general case.  If you expand all realtionships as many to many
then thigs get way to complicated and over general.  The trick is to
know which ones to represient in this way when...
Allan Stanley (Guest)
on 2007-05-24 01:27
You can still achieve reuse and normalization at the object layer -
create a class "Address" and embed this within the Student and School
classes using composite objects (composed_of). This ensures that all
addresses have the same format. To edit addresses in a generic fashion
("click to edit address") you could create an address editor
(controller) that receives the name of the parent class and the record
id. Address validation is provided by a validate method on the Address
class. Or include the address fields within the parent form using a
partial page template.

IMHO collecting all the addresses for all the domain objects into a
single address table is a little over-zealous. It is like taking a
storefront application and extracting all the pricing information
(currency, dollars and cents) into a single price table. Prices should
remain with the items, whether they are catalog items, cart items, order
items, or invoice items. But this is a matter of taste...
Keynan P. (Guest)
on 2007-05-24 03:42
I'm with dom. the solution you seem to want is Multi Table inheritances.
I say solution but it seems inacrurate as you lac an actual problem. the
removal of a school should not trigger the removal of an address as the
building may have been converted to offices(unlikely but possible) in
which case the address is still valid. It would seem to me that the
problem if there is one is in your inflexable database design not the
rails frame work. The one to one relationship of an address to a
structure is one used as example in a book I've been reviewing which
makes this same point. You have given no reason as to why you have
separated out the address. Meaning that this is not a good database
design as it is costing an extra two integers of memory capacity per
school.
Bryan D. (Guest)
on 2007-05-24 19:49
Graham G. <removed_email_address@domain.invalid> <graham.glas wrote:
> For example, if I want to keep a separate addresses table so that, say,
> both schools and students could maintain addresses using the same
> address schema,

This is a *classic* case of over-normalizing. There's, what, 8 fields in
the address schema? Do you really need to go to all the trouble of
maintaining two new relationships and a whole separate table to keep
from putting those 8 fields in both tables?

On top of that, by using a separate table for the address, you're adding
complexity to any and all database operations that involve addresses.
Where a single table approach could look up a school by address in one
super simple query, a two table approach would require an :include
directive and a lot of LEFT JOIN black magic behind the scenes. To
reiterate, this doesn't even gain you any particular benefits.

Finally, you seem very resistant to changing your database schema to
work with the Rails conventions. However, did you ever stop to think
that the reason those conventions exist in the first place (and don't
appear to support your use case) is because your use case is incorrect?
I don't mean to sound offensive, but I think this is the case.
Gabe D. (Guest)
on 2007-05-24 22:48
I think it's pretty dangerous to go down the road of suggesting that
someone is over-normalizing without fully understanding their
application, or even worse, to suggest that ActiveRecord is good enough
for all schemas, and if not then the schema is the problem.

Bryan D. wrote:
>
> This is a *classic* case of over-normalizing. There's, what, 8 fields in
> the address schema? Do you really need to go to all the trouble of
> maintaining two new relationships and a whole separate table to keep
> from putting those 8 fields in both tables?

That really depends on the application.

> On top of that, by using a separate table for the address, you're adding
> complexity to any and all database operations that involve addresses.
> Where a single table approach could look up a school by address in one
> super simple query, a two table approach would require an :include
> directive and a lot of LEFT JOIN black magic behind the scenes. To
> reiterate, this doesn't even gain you any particular benefits.

What if you want to look up all entities with a certain address?  What
if the zipcode changes for the address?    Sure this schema is more
complex, but it also contains more information.  The extra joins are
just the cost of the extra information.  Whether or not the cost is
justified depends on whether that information is necessary.  If it is,
then de-normalizing has higher costs both in terms of query complexity
as well as data maintenance the risk of corruption.

In this case I would tend to agree with you, but don't say there are no
benefits.  It's a legitimate choice.

> Finally, you seem very resistant to changing your database schema to
> work with the Rails conventions. However, did you ever stop to think
> that the reason those conventions exist in the first place (and don't
> appear to support your use case) is because your use case is incorrect?
> I don't mean to sound offensive, but I think this is the case.

On one hand, fudging your schema a little bit to work better with
ActiveRecord is a calculated sacrifice that may well be worth it.  On
the other hand, adopting a worldview that your schema must conform to
the capabilities of AR will result in a dangerous dumbing down of your
data modeling skills.  All ORM is inherently flawed because relational
databases have far far richer semantics for data definition than
objects.  ActiveRecord is nice because it makes the easy things easy,
but it would be folly to think that the hard things can magically be
made easy by ignoring their necessity.

All that said, I think the original poster is wrong to criticize the
semantics of belongs_to.  It's intuitive for most cases. The confusion
arises from the imprecise human language semantics of ownership.  But at
the end of the day you have to know what it means at the database level.
He's wrong to say he "wants AR to support good relational database
design", because it fully supports his use case, just not the way he
imagined it would.  Problem is there are millions and millions of little
edge cases and everyone thinks their's is so common, which is why Java
ORM layers are so overblown and complex.  The bottom line is he's
basically bitching that belongs_to doesn't have :dependent => :destroy,
but that's not trivial to implement as it is for :has_many.  He should
just implement it himself and be done with it.
Bryan D. (Guest)
on 2007-05-25 02:14
Gabe Da silveira wrote:
> I think it's pretty dangerous to go down the road of suggesting that
> someone is over-normalizing without fully understanding their
> application, or even worse, to suggest that ActiveRecord is good enough
> for all schemas, and if not then the schema is the problem.

I was not intending to say that AR is good for everything, or otherwise
it doesn't make sense. What I was trying to say was that particularly,
it *makes sense* that there's no :dependant => :destroy for a belongs_to
precisely because I have difficulty seeing a situation where it makes
sense. The very purpose of belongs_to is to establish a child-parent
relationship of sorts, so you can't know if you can delete the parent.

The fact that the OP wants so dearly to destroy what should be a parent
object indicates pretty clearly to me that there's not additional data
being stored, but rather just normalization. I recognize this particular
pattern because back in the day I considered doing something similar in
a situation where I had several different entities each with exactly one
address. The OO developer in me said I should factor out, but good
database design eventually won out and overruled.

Even if the intention was to actually store additional information, such
as a school having more than one address, then I would say that the
schema was still wrong. If entities can share an address, then there
needs to be a many to many join table. If they can't share them, and
there's more than one address per school, then the address table should
have the foreign key and be doing the belongs_to. If there are many
different entities that might have a parent relationship to addresses,
then the address should probably use a polymorphic relationship.

In any case, I think the schema is in error. If there is more
information concealed somewhere, then I could clearly be wrong.

>> On top of that, by using a separate table for the address, you're adding
>> complexity to any and all database operations that involve addresses.
>> Where a single table approach could look up a school by address in one
>> super simple query, a two table approach would require an :include
>> directive and a lot of LEFT JOIN black magic behind the scenes. To
>> reiterate, this doesn't even gain you any particular benefits.
>
> What if you want to look up all entities with a certain address?  What
> if the zipcode changes for the address?    Sure this schema is more
> complex, but it also contains more information.  The extra joins are
> just the cost of the extra information.  Whether or not the cost is
> justified depends on whether that information is necessary.  If it is,
> then de-normalizing has higher costs both in terms of query complexity
> as well as data maintenance the risk of corruption.

I'd rather do n separate queries (where there are n entities to look up
by address) and then just append the arrays. If you're going to do the
:include for potentially n different relationships, then you are
significantly increasing the complexity of the queries. Even if you
exclude the complexity of the queries as an issue, the complexity of
your object model (and the statements you use to query it) increases.

> On one hand, fudging your schema a little bit to work better with
> ActiveRecord is a calculated sacrifice that may well be worth it.  On
> the other hand, adopting a worldview that your schema must conform to
> the capabilities of AR will result in a dangerous dumbing down of your
> data modeling skills.

I'm not suggesting that the OP fudge their schema at all. I'm suggesting
that it was intrinsically flawed to start with, and that the lack of an
AR way to go about it might be an indication of the problem.
Jurket L. (Guest)
on 2008-08-27 06:19
>
> I'm not suggesting that the OP fudge their schema at all. I'm suggesting
> that it was intrinsically flawed to start with, and that the lack of an
> AR way to go about it might be an indication of the problem.

The original poster is right on. Perhaps the example doesn't make it
clear, so let me present another example.

I have a table called "cities", which is pretty much a static lookup
table. You'll find attributes such as: lat, long, population, name, ...

I have a table called "users" for each user. When a user registers, he
specifies his "city". Essentially a User has-one City.

So now if i add a FK in cities to point back to users, with the
corresponding belongs_to in the city model, rails is happy.

But in my app users go on adventures. When they do, their *current* city
gets copied over into the adventure, so that the adventure remains
static over time (w/respect to city). Eg, a user sets his city to
Chicago on wednesday, on thursday he participates in adventure A1, so
therefore A1's city is "Chicago". On Friday the user changes his
location to Rochester, and then participates in adventure A2. A2's city
is now "Rochester".

So i also have the relationship: Adventure has-one City. But how do i do
this? Do i add a column to Cities called "adventure_id" and the
corresponding belongs_to? That's just ugly. I don't want to keep adding
parent id columns to the city table just because some other entity wants
a relationship with a city.

Do i denormalize and include all of the city attributes in each of User
and Adventure? No way, that's also nasty; consider a user participating
in many adventures over time.

What i really want is to add a column "city_id" to both the User table
and the Adventure table; and whatever other table might be intersted in
having a relationship with City.

In the abstract, this is the notion of a lookup table, where many
entities might have an attribute that is the FK to some specific lookup
table. The FK is in the parent table pointing to the lookup table. This
is a perfectly reasonable relational design.

It's as if AR is missing some sort of "has_reference"; you would only
put this in the parent table. You wouldn't need any sort of "belongs_to"
declaration in the City table, since you wouldn't traverse the model
objects in that direction.

class User
  has_reference :city
end

class Adventure
  has_reference :city
end

class City
 #nothing needed
end
Jeremy K. (Guest)
on 2008-08-27 08:31
(Received via mailing list)
On Tue, Aug 26, 2008 at 7:19 PM, Jurket Largit
<removed_email_address@domain.invalid> wrote:
> put this in the parent table. You wouldn't need any sort of "belongs_to"
>
> class City
>  #nothing needed
> end

"has_reference :city" == "belongs_to :city"

belongs_to :city means you have a foreign key referencing a city, like
users.city_id -> cities.id.

Then, when you create a new adventure, default its starting city to
the user's current city.

Best,
jeremy
Robert W. (Guest)
on 2008-08-27 20:10
Did I miss it or has nobody considered using a polymorphic association
for this case?

class School < ActiveRecord::Base
  has_one :address, :as => :addressable
end

class Student < ActiveRecord::Base
  has_one :address, :as => :addressable
end

Jeremy K. wrote:
> On Tue, Aug 26, 2008 at 7:19 PM, Jurket Largit
> <removed_email_address@domain.invalid> wrote:
>> put this in the parent table. You wouldn't need any sort of "belongs_to"
>>
>> class City
>>  #nothing needed
>> end
>
> "has_reference :city" == "belongs_to :city"
>
> belongs_to :city means you have a foreign key referencing a city, like
> users.city_id -> cities.id.
>
> Then, when you create a new adventure, default its starting city to
> the user's current city.
>
> Best,
> jeremy
This topic is locked and can not be replied to.