决定根据迄今为止收到的反馈和我目前的设置更新此处的信息。
我一直在努力找出解决这个问题的最佳方法,但到目前为止我还没有找到答案。我有两张桌子:顾客和信用卡。一个客户可以有许多credit_card,而一个credit_cad属于一个客户。此外,一个客户可以有许多地址,而一个地址属于一个客户。
在我的信用卡表中,我有一列指示特定的信用卡是否是主要的。列名为primary。客户可以拥有多张信用卡,但只有ONE可以是主要信用卡。
我希望这可以通过验证来完成,但到目前为止,我还是一无所获。我做了很多次搜索,但似乎都不起作用:(
下面的帖子似乎表明了如何做到这一点,但我无法让它发挥作用:验证解决方案?
我的customer.rb模型文件如下。这不是整个代码,而是相关的部分。
class Customer < ActiveRecord::Base
track_who_does_it :creator_foreign_key => "created_by", :updater_foreign_key => "updated_by"
has_many :addresses, :dependent => :destroy
accepts_nested_attributes_for :addresses, :reject_if => lambda { |a| a['name'].blank? }, :allow_destroy => true
has_many :creditcards, :dependent => :destroy
accepts_nested_attributes_for :creditcards, :reject_if => lambda { |a| a['name'].blank? }, :allow_destroy => true
has_one :primary_creditcard, ->{ where(primary: "1") }, class_name: Creditcard, autosave: true
validates :addresses, presence: true
validates :creditcards, presence: true
validates :primary_creditcard, presence: true
end
我的creditcard.rb模型文件如下。
class Creditcard < ActiveRecord::Base
track_who_does_it :creator_foreign_key => "created_by", :updater_foreign_key => "updated_by"
belongs_to :customer
validates :name, presence: true, length: { maximum: 30}
validates :card_type, presence: true
validates :card_number, presence: true
validates :card_exp, presence: true
validates :card_code, presence: true
end
当我创建一个有地址和信用卡的新客户时,我总是会收到一条验证错误消息,内容如下:
主信用卡不能为空
如果能在这方面提供任何帮助,我将不胜感激。
根据请求,从保存数据的控制器添加代码:
if @customer.update_attributes(customer_params)
flash[:success] = 'Member was successfully updated.'
else
flash[:error] = "Member was not updated, please see errors."
end
以上内容在客户控制器的更新部分。
此外,为了参考,customer_params定义如下:
def customer_params
params.require(:customer).permit(:first_name, :last_name, :sex, :dob, :cell_phone, :work_phone, :home_phone, :other_phone, :email1, :email2, :referred_via_id,
:referred_cust_id, :cust_notes,
addresses_attributes: [:id, :customer_id, :name, :line1, :line2, :line3, :city, :county, :state, :zip, :billing, :delivery, :addr_notes],
creditcards_attributes: [:id, :customer_id, :name, :card_type, :card_number, :card_exp, :card_code, :primary])
end
您可以添加一个名为primary_creditcard的附加关系,并验证其存在
class Customer < ActiveRecord::Base
has_many :credit_cards
has_one :primary_creditcard, ->{ where(primary: true) }, class_name: CreditCard
validates :primary_creditcard, presence: true
end