Rails:两个模型之间的多个关系

时间:2014-07-14 08:51:59

标签: ruby-on-rails ruby-on-rails-4 rails-migrations

我在Rails 4.0.4中创建数据库迁移,我希望捕获以下关系:

  

客户有很多信用卡。客户只有一张默认信用卡。

以及我认为它应该是什么样的。

class Customer < ActiveRecord::Base
  has_many :cards
  has_one :card # i.e. has one default card
end

class Card < ActiveRecord::Base
  belongs_to :customer
end

这是对的吗?如果是这样,Rails如何知道belongs_to类中的Card所指的关系?如果不正确(我猜不到),请帮我解决。

3 个答案:

答案 0 :(得分:2)

目前,您的代码足以让has_one :cardhas_many :cards混淆Rails。您应该使用专门为这些类型的关联提供的class_name选项。

这样的事情对你有用

class Customer < ActiveRecord::Base
  has_many :cards
  has_one :default_card, :class_name => "Card"
end

答案 1 :(得分:2)

<强> foreign_key

要添加到Pavan's回答,您需要使用某种条件来确定哪个是default卡。

因为Rails&#39; relational database结构依赖于foreign_keys来提取相关数据,您需要为foreign_key分配正确的default_card,或者使用条件来查找它:

#app/models/customer.rb
Class Customer < ActiveRecord::Base
   has_one :default_card, -> { where default: true" },class: "Card", foreign_key: "customer_id"
end

这将依赖于default

中的布尔列cards

答案 2 :(得分:2)

我把范围放在卡片的一边,对我来说似乎更容易

class Customer < ActiveRecord::Base
  has_many :card
end

class Card < ActiveRecord::Base
  belongs_to :customer
  scope :default, -> { where is_default: true }
end

default_card = customer.cards.default