Rails与模型和迁移的关联 [英] Rails association with models and migration
问题描述
无法理解Rails与模型的关联如何工作.这是一个简单的问题:
Can't understand how Rails association with models works. Here is simple question:
有两个表
产品
id| name | status
1 | Tube | 0
2 | Pillar | 1
3 | Book | 0
4 | Gum | 1
5 | Tumbler | 2
状态
status | name
0 | Unavailable
1 | In stock
2 | Discounted
在型号和控制器上使用〜相同的名称.
With ~ same names for models and controllers.
我不需要在每个新产品的状态表中创建新行.我想在erb中显示状态名称.我应该在模型和迁移文件中写些什么(例如,对于属于归属_,has_one或has_many ...)?
I don't what to create new row in statuses table on every new product. And i want to show status name in erb. What should i write in models and in migration file (for example for which belong_to, has_one or has_many...)?
推荐答案
对于简单的一对多关联,产品应为belongs_to :status
,状态应为has_many :products
,并且您无需设置商品的状态产品.在erb中,您将使用<%= @product.status.name %>
.要设置这些迁移,请create_table :products do |t| t.string :name; t.integer :status_id; end
和create_table :statuses do |t| t.string :name; end
Product should belongs_to :status
and Status should has_many :products
for a simple one-to-many association, and you aren't required to set a status for a product. In erb you'd use <%= @product.status.name %>
. To set up those migrations, create_table :products do |t| t.string :name; t.integer :status_id; end
and create_table :statuses do |t| t.string :name; end
这篇关于Rails与模型和迁移的关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!