Ruby on Rails Tuesday, April 27, 2010

This is a self referential association

class Location < ActiveRecordBase
has_one :south, :class_name => 'Location', :foreign_key => 'south'
end

On Apr 28, 1:58 am, robo <chase.delanguille...@gmail.com> wrote:
> ok, I've got a model called Location, the idea being that i have a
> bunch of locations aligned to a grid.  Each location has a pointer to
> it's neighbors, like so
>
> create_table "locations", :force => true do |t|
>     t.string   "name"
>     t.text     "description"
>     t.integer  "north"
>     t.integer  "northeast"
>     t.integer  "east"
>     t.integer  "southeast"
>     t.integer  "south"
>     t.integer  "southwest"
>     t.integer  "west"
>     t.integer  "northwest"
>     t.integer  "x"
>     t.integer  "y"
>     t.datetime "created_at"
>     t.datetime "updated_at"
>     t.integer  "map_id"
>   end
>
> whereas all the directions (north, south, east, etc) should all be
> references to other locations.
>
> I know this is probably an easy question, but what kind of
> relationship is this, and how would I set it up in my model?  like
> this?
>
> has_one :location, :foreign_key => :north
> has_one :location, :foreign_key => :northeast
> has_one :location, :foreign_key => :east
> has_one :location, :foreign_key => :southeast
> has_one :location, :foreign_key => :south
> has_one :location, :foreign_key => :southwest
> has_one :location, :foreign_key => :west
> has_one :location, :foreign_key => :northwest
>
> --
> You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
> To post to this group, send email to rubyonrails-talk@googlegroups.com.
> To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
> For more options, visit this group athttp://groups.google.com/group/rubyonrails-talk?hl=en.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

No comments:

Post a Comment