Search code examples
ruby-on-railsscaffolding

Generate scaffold which references a model who refers another model


I have 2 existing models: post and post_reply, the latter referring to the former. I want to create another model using scaffolding which references post_reply. What should be the name of my column name in the generate command to refer post_reply correctly?
Using rails 5.


Solution

  • You say "references" and by that I assume you mean belongs_to

    rails generate scaffold new_model post_reply:references
    

    The column name generated will be post_reply_id and you can just create the column directly.

    rails generate scaffold new_model post_reply_id:integer
    

    If you do the latter, you'll need to add the belongs_to line manually to NewModel

    The integer column can actually be called anything you want but calling it post_reply_id is expected and respects the advice of 'convention over configuration'.