【问题标题】:Rails newb - Can you help me with my models?Rails newb - 你能帮我制作模型吗?
【发布时间】:2012-10-12 05:03:36
【问题描述】:

这里的第一个问题是 Ruby 新手,所以请放轻松。在开始之前,我尝试为我的第一个应用绘制一些模型 + 关联,以确保我理解了可以构建的基本概念。

我的模型是否适合我想要完成的任务? 如果没有,有人可以提供一些建议或建议吗? 有没有更简单的方法来做我想做的事情? 从工作流程的角度来看,对于初学者来说,这是一种在缺乏扎实语法的情况下入门的有效方式吗?

谢谢!

【问题讨论】:

  • 客户:它有很多个quote_requests,为什么你通过quote_request_id引用一个报价?同样适用于提供程序中的 quote_id。我认为您可以“看到”它,因为您有两个 x 两个模型,在两个方向(客户/报价请求)和(供应商/报价)都有参考
  • Nippey - 感谢您的反馈...我了解您的问题,但不知道如何回答。代替客户中的单数“quote_request_id”,我应该将其更改为什么,或者如何显示“many”关联?从客户/供应商模型中删除“quote_request_id”和“quote_id”可以吗?
  • 好吧,如果我理解正确的话,我会删除quote_request_id 和quote_id,因为您可以通过从表quote_requests 中选择具有正确customer_id 的报价请求来查找报价请求。那你就不需要上面提到的id了。
  • 任何人回答对您有帮助然后接受该回答

标签: ruby-on-rails associations models


【解决方案1】:

试试这个

class User < ActiveRecord::Base
  has_many :customers
  has_many :providers
end

class Customer < ActiveRecord::Base
  belongs_to :user

  has_many :customer_quote_requests
  has_many :quote_requests, :through => :customer_quote_requests

  has_many :customer_quotes
  has_many :quotes, :through => :customer_quotes
end

class Provider < ActiveRecord::Base
  belongs_to :user

  has_many :provider_quotes
  has_many :quotes, :through => :provider_quotes

  has_many :provider_quote_requests
  has_many :quote_requests, :through => :provider_quote_requests

end

class QuoteRequest < ActiveRecord::Base
  has_many :customer_quote_requests
  has_many :customers :through => :customer_quote_requests

  has_many :provider_quote_requests
  has_many :providers, :through => :provider_quote_requests
end

class CustomerQuoteRequest < ActiveRecord::Base
  belongs_to :customer
  belongs_to :quote_request
end

class Quote < ActiveRecord::Base
  has_many :provider_quotes
  has_many :provider, :through => :provider_quotes

  has_many :customer_quotes
  has_many :customers, :through => :customer_quotes

end

class ProviderQuote < ActiveRecord::Base
  belongs_to :provider
  belongs_to :qoute
end

class ProviderQuoteRequests < ActiveRecord::Base
  belongs_to :provider
  belongs_to :quote_requests
end

class CustomerQuotes < ActiveRecord::Base
  belongs_to :customer
  belongs_to :quote
end

【讨论】:

  • Dipak - 谢谢!如果你还有一秒钟的时间,你能分享一下我为什么不在这里使用“has_many_and_belongs_to”吗?我猜您创建的其他模型满足了我的意图并使其变得不必要......
  • 非常尴尬,我把关联的语法弄错了......'has_and_belongs_to_many' 是我的意思,而不是在我的脑海中翻转它。 :o
  • has_many - through 比 has_many_and_belongs_to 更好,因为看到这个链接 - (1) railscasts.com/episodes/47-two-many-to-many (2) blog.hasmanythrough.com/2007/1/15/…
【解决方案2】:

在您的问题下方对我的 cmets 的一般回答:

如果您有两个具有1:n 关系的表,则不会引用父表中的所有n 元素。您只需定义子表属于哪个1。

在您的情况下: quote_requests 属于 customers。 因此,您通过customer_id 在quote_requests 中引用客户。

这就够了。这样,您就可以拥有属于客户的零个、一个或多个 quote_requests。

(告诉自己一个问题:quote_request_id 如果您有零或多个条目有什么用处?如果您将其设置为零,那么这是引用 id 还是意味着没有分配任何元素?)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 2019-09-13
    相关资源
    最近更新 更多