Ruby on rails 3 rails 3表单上的自定义查找字段
下面是我想做的: 我想要一个基于文本的字段,“优惠券代码” 以嵌套的形式 因此基本上Ruby on rails 3 rails 3表单上的自定义查找字段,ruby-on-rails-3,activerecord,Ruby On Rails 3,Activerecord,下面是我想做的: 我想要一个基于文本的字段,“优惠券代码” 以嵌套的形式 因此基本上f.text\u字段:优惠券 但该值应该是与优惠券表中的项目的关系,而不是按id 优惠券表可能看起来像 |ID| CouponCode | +--+------------+ |1 | a89sd9asda | +--+------------+ |ID| OrderTitle | Coupon | +--+------------+------------+ |1 | sdfsdfsdfd | a89
f.text\u字段:优惠券
但该值应该是与优惠券表中的项目的关系,而不是按id
优惠券表可能看起来像
|ID| CouponCode |
+--+------------+
|1 | a89sd9asda |
+--+------------+
|ID| OrderTitle | Coupon |
+--+------------+------------+
|1 | sdfsdfsdfd | a89sd9asda |
+--+------------+------------+
我的主桌看起来像
|ID| CouponCode |
+--+------------+
|1 | a89sd9asda |
+--+------------+
|ID| OrderTitle | Coupon |
+--+------------+------------+
|1 | sdfsdfsdfd | a89sd9asda |
+--+------------+------------+
rails中有没有一种方法可以通过has\u one链接这两个字段并使用非ID字段?回答您的问题:
class Order < ActiveRecord::Base
has_one :coupon_code, :foreign_key => 'CouponCode'
end
class CouponCode < ActiveRecord::Base
belongs_to :order, :foreign_key => 'CouponCode'
end
类顺序'CouponCode'
结束
类耦合代码'CouponCode'
结束
然而,我同意damien的观点:这看起来有点偏离了常用的db设计方法。如果优惠券表只有一个ID和一个代码,我真的不明白为什么有这个表。只需使用订单表中的CouponCode。是的,它必须匹配优惠券代码数据库tho中的一个优惠券。优惠券是预先生成、分发的,我需要匹配只有一个订单可以有一张优惠券。我是否需要设置:primary_key=>“优惠券”?因为它不会使用优惠券id?