【发布时间】:2013-05-23 19:47:29
【问题描述】:
我正在尝试设置一个系统,让我的帐单配置文件可以通过用户保存地址和付款方式。使用地址,它工作正常,因为用户只有一个,但使用付款方式,因为用户 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
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
【问题讨论】:
-
您需要使用
has_one :payment_method。为了保持一致性(付款方式应该与用户相同),您可以使用自定义验证方法。 -
这不会真正起作用,因为当您对其运行查询时,它会在 PaymentMethods 表中查找不存在的 billing_profile_id。我想在不添加该列的情况下建立关联
标签: ruby-on-rails ruby-on-rails-3 associations relationship