Ruby on rails 如何在Rails中为两个表之间的两种不同类型的关系设置has_many关系?
以下是我的模式:Ruby on rails 如何在Rails中为两个表之间的两种不同类型的关系设置has_many关系?,ruby-on-rails,associations,rails-activerecord,Ruby On Rails,Associations,Rails Activerecord,以下是我的模式: Participant = id: int user_id: int program_id: int ... other fields end User = id: int name: text ... other fields end Program = id: int user_id: int # this is the manager of the program end 因此,用英语: 用户就是人 程
Participant =
id: int
user_id: int
program_id: int
... other fields
end
User =
id: int
name: text
... other fields
end
Program =
id: int
user_id: int # this is the manager of the program
end
因此,用英语:
- 用户就是人
- 程序由用户管理
- 程序也有一组参与者,每个参与者都是用户
class Participant
belongs_to :user
belongs_to
end
class User
has_many :programs
has_many :participants
end
class Program
has_many :participants
belongs_to :user
end
请注意,一个用户确实有很多程序,他们管理的程序,以及通过参与者有很多程序,这些都是他们参与的程序
我想要的是能够说:
- 用户管理程序
- _用户参与_程序
class User
has_many :participations, class_name: "Participant"
has_many :moderated_programs, class_name: "Program", foreign_key: 'moderator_id'
has_many :participating_programs, through: :participations, class_name: "Program", source: :program
end
class Participant
belongs_to :user
belongs_to :program
end
注意第三行。我想要的是利用这一系列关联:参与者有一个用户id和一个程序id。我希望能够说u1.participating\u programs,并获得该用户参与的一个或多个程序的列表,但上述方法不起作用。你能告诉我我在哪里吗?首先,只是一个语言问题:我认为一个用户没有太多的参与者。他是项目的参与者或项目经理。所以他有很多参与 你可以这样写:
class User
has_many :participations, class_name: "Participant"
has_many :managed_programs, class_name: "Program"
end
另外,至少在上面的代码中,参与者类丢失了
belongs_to :user
由于您似乎需要区分两种不同类型的用户,因此
多态性
功能将派上用场。那么您就不需要额外的参与者表了 我同意查尔斯的观点,你的一些措辞/语言问题让人困惑。参与可能是一个更好的术语。我不推荐多态性——用户可能有两个不同的角色,但用户不会是不同的类型。特别是如果管理者也有可能成为参与者
class User
has_many :participations
has_many :programs, through: :participations
has_many :managed_programs, class_name: 'Program'
end
class Program
belongs_to :manager, class_name: 'User'
has_many :participations
has_many :users, through: :participations
end
# Just a join table. Nothing special
class Participation
belongs_to :user
belongs_to :program
end
谢谢是那些拼写错误还是我遗漏了什么?“类:”不应该是“类名称:”?和“:participant”成为“participant”?好的,看起来不错。后续:我想从user->participant->program获得一组该用户参与的程序。这是一个“通过”吗?我该如何表达呢?很好的修饰,我想你回答了我对查理的后续报道你应该接受他的回答,它显示了你所需要的一切。“has_many:managed_programs,class_name:“Program”如何知道它应该在程序中查看的外键称为“user_id”?因为在“类用户”中找到了该子句?因此,如果为了准确起见,我想将程序中的外键更改为“manager\u id”,那么我该怎么办?”有很多:托管程序,类名:'Program',外键:'manager\u id'?我相信如果外键没有明确给出,它会尝试一些提示来找出外键。添加外键:“manager\u id”应该可以。