讓我們創建項目...
rails itunes
cd itunes
創建基本模型:
script/generate model Singer name:string
script/generate model Genre name:string
script/generate model Tag name:string
進行遷移:
rake db:migrate
更新機型:
class Singer < ActiveRecord::Base
has_and_belongs_to_many :genres
end
class Genre < ActiveRecord::Base
has_and_belongs_to_many :singers
has_and_belongs_to_many :tags
end
class Tag < ActiveRecord::Base
has_and_belongs_to_many :genres
end
創建用於連接表兩個遷移:
script/generate migration CreateGenresSingersJoin
script/generate migration CreateGenresTagsJoin
rake db:migrate
的genres_singers模型:
class CreateGenresSingersJoin < ActiveRecord::Migration
create_table 'genres_singers', :id => false do |t|
t.integer 'genre_id'
t.integer 'singer_id'
end
def self.down
drop_table'genres_singers'
end
end
的genres_tags模型:
class CreateGenresTagsJoin < ActiveRecord::Migration
create_table 'genres_tags', :id => false do |t|
t.integer 'genre_id'
t.integer 'tag_id'
end
def self.down
drop_table'genres_tags'
end
end
在seeds.db創建一些播種數據,或無論如何:
Singer.create(:name => 'Lady Ga Ga')
Genre.create(:name => 'Pop')
Genre.create(:name => 'Folk')
Tag.create(:name => 'Top50')
插入一些鏈接數據:
INSERT INTO genres_singers (genre_id, singer_id) VALUES (1, 1)
INSERT INTO genres_singers (genre_id, singer_id) VALUES (2, 1)
INSERT INTO genres_tags (genre_id, tag_id) VALUES (1, 1)
那麼我們可以使用的關聯,如:
Singer.first.genres.first.tags.first
=> #<Tag id: 1, name: "Top50">
Singer.find_by_name("Lady Ga Ga").genres.first.tags
=> [#<Tag id: 1, name: "Top50">]
你想知道如何指定的關聯這一要求或者你想知道做如何使用這些關聯訪問某些數據? – 2010-04-22 00:43:42
我對如何設置關聯感到困惑。 – Dex 2010-04-22 01:14:57