RK

时间:2017-10-24 18:41:14

标签: ruby-on-rails ruby migration

所以,我有第一次使用Ruby on Rails的经验。这是第二个月,但有些事情对我来说仍然有些奇怪。在某些情况下,我可以这样做:

link.url = url

Class Link与Url类具有FK的位置。但在某些情况下,如果我这样做:

equipment.category = category

Rails开始抱怨,说:

ActiveModel::MissingAttributeError: can't write unknown attribute `equipment_id`

为什么会这样?每次我必须在表格中做一些关于我所做的参考的改变:

add_reference :equipment, :category, foreign_key: true

那么我怎么能像第一个例子那样做所有的Classes / Table行为呢?

编辑1:

我的类别和设备架构是这样的:

create_table "categories", force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
end

create_table "equipment", force: :cascade do |t|
    t.string "title"
    t.text "description"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "category_id"
    t.index ["category_id"], name: "index_equipment_on_category_id"
end

编辑2 类中的关联是这样的:

class Category < ApplicationRecord
    # Associations
    has_many :equipment
    ...

class Equipment < ApplicationRecord
    # Associations
    has_one :category
    ...

1 个答案:

答案 0 :(得分:2)

您希望将belongs_to用于具有外键的类sp:

class Category < ApplicationRecord
    # Associations
    has_many :equipment
    ...

class Equipment < ApplicationRecord
    # Associations
    belongs_to :category
    ...

你可能也会遇到麻烦,因为equipmentan irregularly inflected noun - 它在Rails中是它自己的复数。对表格/模型使用这种单词通常涉及到我的试错,最终可能比它的价值更麻烦。