Scaffolding ActiveRecord: two columns of the same data type

前端 未结 3 1711
旧时难觅i
旧时难觅i 2020-12-16 11:41

Another basic Rails question:

I have a database table that needs to contain references to exactly two different records of a specific data type.

Hypothetical

3条回答
  •  没有蜡笔的小新
    2020-12-16 11:50

    I have no idea how to do this with script/generate.

    The underlying idea is easier to show without using script/generate anyway. You want two fields in your videogames table/model that hold the foreign keys to the companies table/model.

    I'll show you what I think the code would look like, but I haven't tested it, so I could be wrong.

    Your migration file has:

    create_table :videogames do |t|
      # all your other fields
      t.int :developer_id
      t.int :publisher_id
    end
    

    Then in your model:

    belongs_to :developer, class_name: "Company", foreign_key: "developer_id"
    belongs_to :publisher, class_name: "Company", foreign_key: "publisher_id"
    

    You also mention wanting the two companies to be distinct, which you could handle in a validation in the model that checks that developer_id != publisher_id.

提交回复
热议问题