rails 3表单上的自定义查找字段

时间:2012-04-25 21:56:51

标签: ruby-on-rails-3 activerecord

所以我正在尝试做什么:

我想要一个基于文字的字段,“优惠券代码”

以嵌套形式。

基本上f.text_field :coupon

但该值应该是与coupons表中的项目的关系,而不是与id的关系。

优惠券表可能看起来像

|ID| CouponCode |
+--+------------+
|1 | a89sd9asda |
+--+------------+

我的主表看起来像

|ID| OrderTitle |   Coupon   |
+--+------------+------------+
|1 | sdfsdfsdfd | a89sd9asda |
+--+------------+------------+

在rails中是否有办法通过has_one链接这两个并使用非ID字段?

1 个答案:

答案 0 :(得分:1)

回答你的问题:

class Order < ActiveRecord::Base
   has_one :coupon_code, :foreign_key => 'CouponCode'
end

class CouponCode < ActiveRecord::Base
   belongs_to :order, :foreign_key => 'CouponCode'
end    

然而,我同意达米恩:这看起来有点像常见的数据库设计方法。

相关问题