【问题标题】:How to correctly set up model associations如何正确设置模型关联
【发布时间】:2016-03-08 07:00:02
【问题描述】:

我希望user 能够创建和保存或选择现有的client 添加到发票中。每张发票只能有一个client

我目前有 3 个模型 users invoicesitems 我目前使用的是简单的has_many 关系,但现在我很困惑,因为我想添加一个新表clients。我希望我能得到一些关于使用什么协会的建议。

我目前的联想

class User < ActiveRecord::Base
has_many :invoices

class Invoice < ActiveRecord::Base
belongs_to :user
has_many :items, :dependent => :destroy

class Item < ActiveRecord::Base
belongs_to :invoice

所以我想做一些简单的事情,比如添加has_many :clientsusers,添加has_one :clientinvoices 并添加表格clients

class User < ActiveRecord::Base
has_many :invoices
has_many :clients

class Client < ActiveRecord::Base
belongs_to : user

class Invoice < ActiveRecord::Base
belongs_to :user
has_many :items, :dependent => :destroy
has_one :client

这行得通吗?有没有更好的办法?

【问题讨论】:

  • 你想达到什么目的?
  • 为了清楚起见更新了问题

标签: ruby-on-rails ruby-on-rails-4 model associations


【解决方案1】:

您很少会使用has_one。在您的情况下,以下模型更有意义:

class User < ActiveRecord::Base
  has_many :invoices
end

class Invoice < ActiveRecord::Base
  belongs_to :user
  belongs_to :client
  has_many :items, :dependent => :destroy
end

class Item < ActiveRecord::Base
  belongs_to :invoice
end

class Client < ActiveRecord::Base
  has_many :invoices
  has_many :items, through: :invoices
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-23
    • 2021-01-18
    相关资源
    最近更新 更多