我有User
模型和Dispute
模型。争议包含一个涉及用户的列表,以及一个"原告"和#34;被告"。我希望能够做到这一点:
Dispute.first.users
#[<User 1>, <User 2>]
Dispute.first.accuser
#<User 1>
Dispute.first.defendant
#<User 2>
所以这是我的模特:
class Dispute < ApplicationRecord
has_and_belongs_to_many :users
belongs_to :accuser, polymorphic: true
belongs_to :defendant, polymorphic: true
end
class User < ApplicationRecord
has_and_belongs_to_many :disputes
has_one :user, as: :accuser
has_one :user, as: :defendant
end
迁移:
class CreateDisputes < ActiveRecord::Migration[5.0]
def change
create_table :disputes do |t|
t.references :accuser, polymorphic: true, index: true
t.references :defendant, polymorphic: true, index: true
end
end
end
class CreateUsers < ActiveRecord::Migration[5.0]
def change
create_table :users do |t|
t.timestamps
end
end
end
除非我将用户分配到Dispute.new.save
和dispute.accuser
,否则这会向我提供我想要的行为,除非dispute.defendant
出错。
它看起来也是错误的:用户 我似乎无法让它工作。
答案 0 :(得分:4)
我可以提出更简单的建议吗?我希望我做对了。
型号:
class Dispute < ApplicationRecord
belongs_to :accuser, class_name: 'user'
belongs_to :defendant, class_name: 'user'
def users
[accuser, defendant]
end
end
class User < ApplicationRecord
end
迁移:
class CreateDisputes < ActiveRecord::Migration[5.0]
def change
create_table :disputes do |t|
t.references :accuser, index: true, references: :user
t.references :defendant, index: true, references: :user
end
end
end