2012-03-24 148 views
1

我想了解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列标识,并使用该列我需要获取属于单个组的事件! 我该如何做到这一点!

+0

你不必明确指明了'belongs_to'了'foreign_key'名如果它是你的形式('associationname_id')。 – 2012-03-24 19:14:11

回答

2

我看到你的group_id和event_id是你的迁移中的字符串,所以我想你可能会缺少一个rails约定。轨道惯例是,所有的表都有一个名为整型的ID的主键,任何外键由模型的名称引用它,奇,+ _id:

table groups: 
    id: integer 
    name: string 


table events: 
    id: integer 
    name: string 
    group_id: integer 

从这个惯例,所有你必须在你的模型指定为:

class Event < ActiveRecord::Base 
    belongs_to :group 
end 

class Group < ActiveRecord::Base 
    has_many :events 
end 

此时,铁轨知道通过约定优于配置:若要查找事件的组,它知道如何寻找GROUP_ID(单数)来指代groups.id(复数表名)

event = Event.first #=> returns the first event in database 
group = event.group #=> returns the group object 

同样,知道如何找到一组

group = Group.first #=> returns first group in database 
group.events   #=> returns an Enumerable of all the events 

中的所有事件有关详细阅读,阅读rails guide on associations

+0

thnx DGM,我仍然需要添加事件到一个组的基础上的组ID,这需要一个字符串...所以我有这样的组:group A - group_id:“音乐”,组B - group_id:“技术“,然后我需要根据group_id向这些组添加事件 – bytebiscuit 2012-03-24 19:59:15

+0

您需要搜索具有所需名称的组,然后使用它创建事件。例如,'Group.where(:title =>'music')。首先<< Event.new(event_attributes)' – DGM 2012-03-25 04:46:31

+0

没有任何办法可以通过关联完成此操作......不必依赖于.where ?可能通过一个外键!? – bytebiscuit 2012-03-25 04:53:44