Rails association with models and migration

 ̄綄美尐妖づ 提交于 2019-12-24 17:12:43

问题


Can't understand how Rails association with models works. Here is simple question:

There are two tables

products

id|   name  | status
1 | Tube    | 0
2 | Pillar  | 1
3 | Book    | 0
4 | Gum     | 1
5 | Tumbler | 2

statuses

status | name
0      | Unavailable
1      | In stock
2      | Discounted

With ~ same names for models and controllers.

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...)?


回答1:


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

more information here




回答2:


First of all for in accordance with rails conventions you need to rename product.status to product.status_id.

product belongs_to :status
status has_many :products

Product.find(1).status.name should be 'Unavailable'




回答3:


If you understand the basics of relational database then it's pretty much the same thing.
When you say, status belongs_to :product and product has_many :statuses, it essentially means status table has a foreign key which you can use to retrieve all status rows for a given product id.

To establish this relationship, you'll need to create a new column product_id in your statuses table:

rails g migration AddProductIdToStatuses product_id:integer

Once done, add the following in your product.rb:

has_many :statuses

and this in your status.rb:

belongs_to :product


来源:https://stackoverflow.com/questions/19409912/rails-association-with-models-and-migration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!