Rails 协会有 one/belongs vs 有 many/belongs

Rails association for has one/belongs to vs has many/belongs to

我想创建两个table,一个是Job,一个是JobType。

每个工作都有一个 job_type 即。临时工、兼职或全职。

class Job < ApplicationRecord
  has_one :job_type
end

class JobType < ApplicationRecord
  belongs_to :job
end

所以我的 job_type table 看起来像这样

id  type    job_id
1   temp      1
2   temp      2
3   fulltime  3
4   temp      4

好像有点多余...

我应该改为做,工作属于 job_type 而 job_type 有很多这样的工作吗?

id   name   job_type_id
1   waiter    1
2   waiter    2
3   clerk     1

id   type  
1    temp
2    fulltime

我很困惑。任何帮助表示赞赏。谢谢。

一个Job可以有很多job types,关联会像

class Job < ApplicationRecord
  has_many :job_type
end

class JobType < ApplicationRecord
  belongs_to :job
end

否则你可以给出关联,比如一份工作有很多 job_types 和一份 job_type 有很多工作。

class Job < ApplicationRecord
  has_and_belongs_to_many :job_type
end

class JobType < ApplicationRecord
  has_and_belongs_to_many :job
end

这个问题适合many-to-many relationship
一个jobhas_manyjob_types,任意一个job_type都可以has_mayjobs.

为此,您需要加入 table - jobs_jobs_types

您的数据将如下所示:

jobs
id   name   
1   waiter  
2   clerk   

jobs_types
id   type  
1    temp
2    fulltime

jobs_jobs_types
job_id job_type_id
1 1
1 2
2 1

我会把代码留给你。 :) 您可以在此 Railscast.

中获得更多帮助

Ruby只是一种简单的编程语言。正如我们所说,它完全有效。

For eg: A Posts has_many Comments and Comments belongs_to Post.

在这里你可以清楚地看到这里的多元化告诉我们,有很多针对特定 post 的评论。 同样的想法适用于 has_one 关系、用户 has_many 投票和投票 belongs_to 用户。 因此,在你的情况下,我建议你将你的协会写成 工作 has_many 类型和 job_types 属于工作。

所以这里的 job_types table 将使用您的 table 作业的主键作为数据规范化的外键。