How to assign a has_many/belongs_to relation properly in Rails ActiveRecord?

前端 未结 4 1055
一整个雨季
一整个雨季 2021-01-12 06:46

I have a rails app with articles and author model. If I have an author and a post and want to indicate that the author should be the owner of the article, or that the articl

4条回答
  •  一向
    一向 (楼主)
    2021-01-12 07:20

    I'm assuming you mean author_one.articles << my_article rather than just author_one << my_article

    One difference between the two is that

    author_one.articles << my_article
    

    will save the change to the database immediately. i.e. it will either create the record for my_article if it has not been saved before or it will update the existing record to have author_id = author_one.id

    whereas

    my_article.author = author_one
    

    or

    my_article.author_id = author_one.id
    

    will not be persisted until you do a my_article.save

提交回复
热议问题