Rails与模型和迁移相关联
无法理解Rails如何与模型联系起作用。 这是一个简单的问题:
有两张桌子
制品
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
与模型和控制器相同的名称。
我不知道在每个新产品的状态表中创建新行的内容。 我想在erb中显示状态名称。 我应该在模型和迁移文件中写什么(例如,belongs_to,has_one或has_many ……)?
产品应该belongs_to :status
和Status应该has_many :products
用于简单的一对多关联,并且您不需要为产品设置状态。 在erb中,你使用<%= @product.status.name %>
。 要设置这些迁移, create_table :products do |t| t.string :name; t.integer :status_id; end
create_table :products do |t| t.string :name; t.integer :status_id; end
create_table :products do |t| t.string :name; t.integer :status_id; end
和create_table :statuses do |t| t.string :name; end
create_table :statuses do |t| t.string :name; end
更多信息在这里
首先,根据rails约定,您需要将product.status重命名为product.status_id。
产品belongs_to:status
状态has_many:产品
Product.find(1).status.name应为’不可用’
如果您了解关系数据库的基础知识,那么它几乎是一样的。
当你说status belongs_to :product
和product has_many :statuses
status时,它实质上意味着状态表有一个外键,你可以用它来检索给定产品id的所有状态行。
要建立此关系,您需要在状态表中创建新列product_id
:
rails g migration AddProductIdToStatuses product_id:integer
完成后,在product.rb中添加以下内容:
has_many :statuses
这在你的status.rb中:
belongs_to :product