【发布时间】:2016-03-23 23:04:47
【问题描述】:
一段时间以来,我一直在为这个应用程序的建模和初始种子过程苦苦挣扎。我想在Event 和Artist 之间制作一个联合表EventArtist,这样就可以检索任何活动阵容中的所有艺术家以及艺术家参加的所有活动。如何添加多个artist_ids 到一个事件?
这是种子文件:
venue = Venue.create(name: "Speakeasy", address: "Lynwood Ave", zip_code: "30312")
artist = Artist.create(name: "DJ Sliink", bio: "jersey club king")
artist2 = Artist.create(name: "DJ Spinn", bio: "Teklife's chief spokesperson")
#this is probably wrong
lineup = EventArtist.create({artist_id: artist.id}, {artist_id: artist2.id})
event = Event.create(name: "Dance your ass off",
date: DateTime.new(2016,2,3,10,0,0,'+7'),
venue: venue,
#this right here... how?
artist_id: ,
description: "free free free")
这里是架构的相关部分
create_table "event_artist", id: false, force: :cascade do |t|
t.integer "artist_id"
t.integer "event_id"
end
add_index "event_artist", ["artist_id"], name: "index_event_artist_on_artist_id", using: :btree
add_index "event_artist", ["event_id"], name: "index_event_artist_on_event_id", using: :btree
create_table "events", force: :cascade do |t|
t.string "name"
t.datetime "date"
t.text "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "venue_id"
end
add_index "events", ["venue_id"], name: "index_events_on_venue_id", using: :btree
型号:
class Event < ApplicationRecord
belongs_to :venue
has many :artists, through :event_artists
end
class EventArtist < ApplicationRecord
belongs_to :event
belongs_to :artist
end
class Artist < ApplicationRecord
has_many :events, through: :event_artists
end
【问题讨论】:
标签: ruby-on-rails has-many-through seeding