当模型has_many时,Has_One通过模型

时间:2013-05-23 19:47:29

标签: ruby-on-rails ruby-on-rails-3 associations relationship

我正在尝试设置一个系统,我的结算资料可以通过用户持有地址和付款方式。使用地址,它工作正常,因为用户只有一个,但使用付款方式,因为用户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?**

BillingProfile

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

BillingProfile表

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

知道如果这是可能的,或者是否有更好的方法来接近它?我在创建账单配置文件时只涉及手动设置id的想法,但后来我必须创建方法来获取付款方法并不可怕但是如果Rails能够做到这一点就很好我

修改

所以,因为看起来我所希望的是不可能的。我简单地向Billing Profile添加了一个方法来模拟关联。

def payment_method
    PaymentMethod.find(payment_method_id)
  end 

1 个答案:

答案 0 :(得分:2)

:through选项用于链接关系。所以,以下是正确的:

billing_profile.user.address == biling_profile.address

但是,以下情况不可能是正确的(因为您只需要一方在一方而另一方只有一个列表):

billing_profile.user.payment_methods == billing_profile.payment_method

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

因此,简而言之,您需要添加has_onebelong_to而不添加:trhough,并添加新列(额外内存)以保持此关系。

相关问题