0

我正在尝试建立一个系统,我的帐单配置文件可以通过用户保存地址和付款方式。使用地址,它可以正常工作,因为用户只有一个但使用付款方式,因为用户 has_many,我不断收到错误:

ActiveRecord::HasManyThroughSourceAssociationNotFoundError: 
Could not find the source association(s) :payment_method_id in model User. 
Try 'has_many :payment_method, :through => :user, :source => <name>'. 
Is it one of :address, :billing_profile, or :payment_methods?**

计费资料

class BillingProfile < ActiveRecord::Base
  attr_accessible :user, :payment_method
  belongs_to :user
  has_one :address, :through => :user
  has_one :payment_method, :through => :user
end

用户

class User < ActiveRecord::Base
  ...

  has_one :billing_profile

  has_many :payment_methods

  has_one :address, :as => :addressable
  accepts_nested_attributes_for :address
end

地址

class Address < ActiveRecord::Base
  belongs_to :addressable, :polymorphic => true

  attr_accessible :city, :country, :state, :street_line_1, :street_line_2, :zip_code
end

付款方式

class PaymentMethod < ActiveRecord::Base
  attr_accessible :user_id, :is_default

  belongs_to :user

  validates_presence_of :user_id
end

计费资料表

create_table :billing_profiles do |t|
  t.integer :user_id
  t.integer :payment_method_id
  t.timestamps
 end

知道这是否可能,或者是否有更好的方法来解决它?当我创建计费配置文件时,我曾尝试过仅手动设置 id 的想法,但随后我必须创建方法来获取付款方式,这并不可怕,但如果 R​​ails 能够做到这一点,那就太好了我。

编辑

因此,既然看来我所希望的似乎是不可能的。我简单地向 Billing Profile 添加了一个方法来模拟关联。

def payment_method
    PaymentMethod.find(payment_method_id)
  end 
4

1 回答 1

2

:through选项用于链接关系。因此,以下情况成立:

billing_profile.user.address == biling_profile.address

但是,以下情况不可能是真的(因为您只想要一个在一侧,而在另一侧有一个列表):

billing_profile.user.payment_methods == billing_profile.payment_method

您需要一个额外的列来建立这种关系。如果两者返回相同,则只能使用该:through关系,因为没有“额外内存”来仅保存列表中的一个。

所以,简而言之,你需要添加一个has_one或一个belong_to没有:trhough,并添加一个新列(额外的内存)来保持这种关系。

于 2013-05-23T20:04:21.590 回答