Adding a Model Reference to existing Rails model

后端 未结 3 1780
情深已故
情深已故 2021-02-01 04:15

I\'d like to know the \"proper\" way to approach adding a relation between two existing classes in Rails 3.

Given existing models: Clown & Rabbit

I\

相关标签:
3条回答
  • 2021-02-01 04:32

    If you are using edge rails (4.0) you can use:

    rails generate migration AddAddressRefToContacts address:references
    

    As you can see by the docs.

    0 讨论(0)
  • 2021-02-01 04:42

    I'm not sure where you got this idea, but there is no (and never has been) such syntax to do what you want with add_column. To get the behavior you want, you'd have to do t.refences :clown, as you stated. In the background this will call: @base.add_column(@table_name, "#{col}_id", :integer, options).

    See here.

    EDIT:

    I think I can see the source of your confusion. You saw the method call t.reference and assumed it was a datatype because calls such as t.integer and t.string exist, and those are datatypes. That's wrong. Reference isn't a datatype, it's just simply the name of a method, similar to t.rename is.

    0 讨论(0)
  • 2021-02-01 04:43

    After you set belongs_to in Rabbit, and has_many in Clown, you can do a migration with:

    add_column :rabbit, :clown_id, :integer
    

    EDIT: See Paulo's answer below for a more updated answer (Rails 4+)

    0 讨论(0)
提交回复
热议问题