我正在构建一个时间跟踪器。您可以创建时间戳,其中包含此客户的开始时间、结束时间、客户和项目。因此,您可以看到您在项目或客户上花费了多少时间。
带有"has_many"的表之间的关系效果很好,但我对"has_one"关系有问题。
我的桌子:
timestamps customers projects
---------- ------------ -----------
id:integer id:integer id:integer
desc:string customer_name:string project_name:string
customer_id:interger project_id:integer
我的模型:
时间戳.rb
class Timestamp < ActiveRecord::Base
has_one :customer
has_one :project, through: :customer
end
客户.rb
class Customer < ActiveRecord::Base
belongs_to :timestamp
has_many :projects, dependent: :destroy
end
项目.rb
class Project < ActiveRecord::Base
belongs_to :customer
end
我的目标:
- 创建一个时间戳,其中包含关联的客户和项目:
Timestamp.create({desc: "Something", customer_id: "1", project_id: "6"})
- 从时间戳获取项目:
Timestamp.find(1).customer.project
我的问题:
如果我在项目表中包含一个timestamp_id,我可以完成这项工作,但是使用这种方法,当我创建新时间戳时,Rails 会复制具有特定timestamp_id的每个项目。但是我想为时间戳分配一个project_id。
仅供参考:我正在使用带有 MYSQL 数据库的 rails 4.2.6。
由于您不希望每个时间戳具有重复的项目和重复的客户,因此只需将外键设置为时间戳。这样,您可能希望具有具有以下列的表:
Timestamps
customer_id:integer:index
project_id:integer:index
Customers
Projects
customer_id:integer:index
您必须编写和运行迁移以删除列,并添加列以使其显示在上方。
然后,修改关联:
class Timestamp < ActiveRecord::Base
belongs_to :customer # change to belongs_to
has_many :projects, through: :customer # you might not need this anymore because of the line below
belongs_to :project # add this line
end
class Customer < ActiveRecord::Base
has_one :timestamp # change to has_one
has_many :projects, dependent: :destroy
end
class Project < ActiveRecord::Base
belongs_to :customer
has_one :timestamp # add this line
end
然后,您现在可以使用以下
Timestamp.find(1).customer
Timestamp.find(1).project
Timestamp.find(1).projects # these projects are customer.projects and are not directly associated to the line above, so I don't think you would need to call this
好的,谢谢大家! @Jay-Ar Polisario,你的回答并不完美,但它让我想到了我的"has_one/has_many"关系,正因为如此,经过数小时的重新思考,它才起作用。谢谢。
对于从谷歌来到这里寻找类似问题的答案的每个人:
继续开始在黑板或纸上绘制表格和列。使关系可视化!这帮助我找到了正确的关系。