[英]How does the relationship between 2 tables in Rails models?
I have 2 tables in Rails: 我在Rails中有2个表:
CURRENCIES: ------------- | id | name | ------------- | 1 | USD | | 2 | EUR | -------------
ITEMS: ---------------------------------------- | id | name | price | currency_id | ---------------------------------------- | 1 | product a | 100 | 1 | | 2 | product b | 20 | 2 | | 3 | product c | 60 | 2 | | 4 | product d | NULL | NULL | ----------------------------------------
ITEMS.price
and ITEMS.currency_id
are allow NULL
, but ITEMS.currency_id
must be set when ITEMS.price != NULL
. ITEMS.price
和ITEMS.currency_id
是允许NULL
,但ITEMS.currency_id
必须设置时ITEMS.price != NULL
。
How does the relationship between those tables? 这些表之间的关系如何?
This is how you should do the one-to-one relationship in RoR: 这是您应该在RoR中进行一对一关系的方式:
class Item < ActiveRecord::Base
has_one :currency
end
Depending on your DBMS, you could add a check constraint so that price
and currency_id
must be either both null or both with a value. 根据您的DBMS,您可以添加检查约束,以使
price
和currency_id
必须均为null或均带有值。
It also seems to me you could put that in another table 在我看来,你也可以把它放在另一个桌子上
PRICES
---------------------------
| id | value | currency_id |
---------------------------
| 1 | 100 | 1 |
| 2 | 200 | 2 |
---------------------------
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.