model reference

11 views
Skip to first unread message

tanizawa

unread,
Jun 18, 2012, 1:38:21 AM6/18/12
to rubyonra...@googlegroups.com
hi

I am tanizawa
I am searching how to add  reference of two same table.
Please teach me how to add .
exmple:
class CreateLocationjs < ActiveRecord::Migration
  def change
    create_table :locationjs do |t|
      t.references :locationm  <----start point
                                         <--- I want to add  end point  field.

Patrick Mulder

unread,
Jun 18, 2012, 5:52:53 AM6/18/12
to rubyonra...@googlegroups.com
Not sure what your exact question is, but this example below
references a location 2 times:

# Create models:
rails g model location name:string
rails g model route

# Add associations between models:
in Location, add:
has_many :routes

in Route, add:
belongs_to :location_start, :class_name => Location, :foreign_key
=> "location_start_id"
belongs_to :location_end, :class_name => Location, :foreign_key
=> "location_end_id"

# Define foreign keys in db migration:

class CreateRoutes < ActiveRecord::Migration
def change
create_table :routes do |t|
t.references :location_start
t.references :location_end

t.timestamps
end
end
end

# Now in console:
munich = Location.new
munich.name = "Munich"; munich.save!

tokyo = Location.new
tokyo.name = "Tokyo"; tokyo.save!

route = Route.new
route.location_start = munich
route.location_end = tokyo
route.save!

tanizawa kazuya

unread,
Jun 18, 2012, 9:43:22 AM6/18/12
to rubyonra...@googlegroups.com
Thank you for your code.
I couldn't have done it without you.
I understand how to add some reference for same table.

2012/6/18 Patrick Mulder <mulder....@gmail.com>

--
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 rubyonra...@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-ta...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.


Reply all
Reply to author
Forward
0 new messages