0
我想種子GroupItem記錄,但我沒有提供正確的數據到創建方法。多態協會,創建一個記錄
下面是我在軌控制檯嘗試:
irb(main):055:0> group = Group.first
Group Load (0.2ms) SELECT "groups".* FROM "groups" ORDER BY "groups"."id" ASC LIMIT ? [["LIMIT", 1]]
=> #<Group id: 1, groupable_type: "Legislator", name: "Cool Peeps", created_at: "2017-02-23 01:13:21", updated_at: "2017-02-23 01:13:21">
irb(main):056:0> person = Role.first
Role Load (0.2ms) SELECT "roles".* FROM "roles" ORDER BY "roles"."role_id" ASC LIMIT ? [["LIMIT", 1]]
=> #<Role role_id: 100, caucus: nil, congress_numbers: "[106]", current: false, description: "Representative for Wisconsin's 2nd congressional d...", district: 2, enddate: "2001-01-03", address: nil, contact_form: nil, fax: nil, office: nil, rss_url: nil, how: nil, leadership_title: nil, party: "Democrat", person_id: 400013, phone: nil, role_type: "representative", role_type_label: "Representative", senator_class: nil, senator_rank: nil, startdate: "1999-01-06", state: "WI", title: "Rep.", title_long: "Representative", website: "", created_at: "2017-02-23 01:11:08", updated_at: "2017-02-23 01:11:08">
irb(main):059:0> GroupItem.create(group_id: group.id, groupable_type: group.groupable_type, groupable_id: person.id)
(0.1ms) begin transaction
Legislator Load (0.1ms) SELECT "legislators".* FROM "legislators" WHERE "legislators"."id" = ? LIMIT ? [["id", 100], ["LIMIT", 1]]
Group Load (0.1ms) SELECT "groups".* FROM "groups" WHERE "groups"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
(0.1ms) rollback transaction
=> #<GroupItem id: nil, group_id: 1, groupable_type: "Legislator", groupable_id: 100, created_at: nil, updated_at: nil>
這裏是設置:
class Group < ApplicationRecord
has_many :group_items
end
class GroupItem < ApplicationRecord
belongs_to :groupable, polymorphic: true
belongs_to :group
end
class Role < ApplicationRecord
belongs_to :person, foreign_key: :person_id
has_many :group_items, as: :groupable
#....
end
# migrations...
class CreateGroups < ActiveRecord::Migration[5.0]
def change
create_table :groups do |t|
t.string :name
t.timestamps
end
end
end
class CreateGroupItems < ActiveRecord::Migration[5.0]
def change
create_table :group_items do |t|
t.integer :group_id
t.references :groupable, polymorphic: true, index: true
t.timestamps
end
end
end
class CreateRoles < ActiveRecord::Migration[5.0]
def change
create_table :roles, :id => false do |t|
t.primary_key :role_id
#...
t.timestamps
end
end
end
它必須與協會的一個問題,這是我的第一次創業到多態所以我可能搞砸了一些東西。
會發生什麼事,如果你做'group_item.errors.full_messages.to_sentence'?另外,你的'groupable_type'是一個'Group',但你的'groupable_id'是一個'Person'嗎? –
是的,我把多態關聯放在Group上而不是GroupItem上。 –