2015-04-14 38 views
0

我想创建两个模型之间的多对多关系,我想逐步了解要做什么。我想解释如何进行迁移,以及如何理想地创建模型。我想要现在做的方式是:已经属于很多Rails 4

rails g model Location name:string 
rails g model Datetime date:datetime 

现在我要打开最近创建的模型,并添加:

//models/location.rb 
class Location < ActiveRecord::Base 
    has_and_belong_to_many :datetimes 
end 

//models/datetime.rb 
class Datetime< ActiveRecord::Base 
    has_and_belong_to_many :locations 
end 

我在Ruby命令行创建两个模型

现在显然我必须做一个迁移,但我不明白它是什么,我猜一些最老的版本的来源真的让我感到困惑。有人可以请详细解释吗?

Obs:还有一些类似的问题但是他们不回答我的问题,因为他们没有深入解释要做什么。

+0

http://guides.rubyonrails.org/association_basics.html – NorCalKnockOut

+0

我读过,但我仍然不明白:/ –

回答

1

至于建议由红宝石教程中,我们产生新的迁移:

rails g migration CreateDatetimesAndLocations 

这种迁移我有内幕:

class CreateDatetimesAndLocations < ActiveRecord::Migration 
    def change 
     create_table :locations_datetimes, id:false do |t| 
     t.belongs_to :datetime, index: true 
     t.belongs_to :location, index: true 
     end 
    end 
end 

这也正是做过类似的红宝石教程。现在我有这个控制器,我正在测试上,它是这样说:

class WeatherController < ApplicationController 
    def data 
    @location = Location.new 
    @location.name = "test" 
    @datetime = Datetime.new 
    @datetime.date = DateTime.new(2001,2,3) 
    @location.datetimes << @datetime // **PROBLEM ON THIS LINE** 
    @location.save 

    @location = Location.new 
    @location.name = "teste2" 
    @location.locations << @location 
    @locations = Location.all //(show locations in view) 
    end 
end 

我遇到的问题是因为locations_datetimes必须datetimes_locations(按字母顺序显然)。