我想了解Rails如何在外键和主键方面工作。来自纯SQL背景的Rails方法对我来说似乎非常陌生。 我有以下两个迁移:RoR中的模型协会
组
class CreateGroups < ActiveRecord::Migration
def self.up
create_table :groups do |t|
t.string :title
t.text :description
t.string :city
t.integer :event_id
t.string :zip
t.string :group_id
t.text :topics
t.timestamps
end
end
def self.down
drop_table :groups
end
end
和事件:
class CreateEvents < ActiveRecord::Migration
def self.up
create_table :events do |t|
t.string :title
t.string :description
t.string :city
t.string :address
t.time :time_t
t.date :date_t
t.string :group_id
t.timestamps
end
end
def self.down
drop_table :events
end
end
一个组可以有许多事件和事件可以属于一个组。我有以下两种模式:
class Event < ActiveRecord::Base
belongs_to :group, :foreign_key => 'group_id'
end
和
class Group < ActiveRecord::Base
attr_accessible :title, :description, :city, :zip, :group_id, :topics
has_many :events
end
不知道如何指定外键和主键此。例如,一个组由group_id列标识,并使用该列我需要获取属于单个组的事件! 我该如何做到这一点!
你不必明确指明了'belongs_to'了'foreign_key'名如果它是你的形式('associationname_id')。 – 2012-03-24 19:14:11