2017-04-30 65 views
0

我有两个模型UserPostconditional get_or_create Rails 5

Post有一个属性status,其中将是draftpublished

我想确保User只有一个帖子发布了status

有没有什么内置的轨道,这样做?像get_or_create基于条件?

+0

有一个叫'方法find_or_create_by',也许这件事情,可以帮助你 – Iceman

+0

我试过'find_or_create_by_status(“出版”)',但没有奏效。 – static

+2

'find_or_create_by(status:'published')'是正确的语法 – Iceman

回答

1

您可以使用一种名为find_or_create_by的方法,该方法根据给定条件在数据库中查找记录,并返回它或在没有记录的情况下创建一个新记录。

一个例子

u = User.find_or_create_by(status: 'published')