ruby 连接两个模型中的电子邮件字段(Find_each产生堆栈太深错误)

sqserrrh  于 2023-08-04  发布在  Ruby
关注(0)|答案(1)|浏览(110)

我有两个模型(AuthorUser),它们都有email字段。Userhas_manyAuthorsAuthor应属于User
我需要找到一种方法来查看数据,并在匹配时将author.user_id设置为相应的user.id
理论上,它可以使用我在author.rb模型中放入的connect_to_user方法:

def connect_to_user
    User.find_each do |user|
      if self.email == user.email
        self.update(user_id: user.id)
      end

      if user.chosen_author_id == nil
        user.update(chosen_author_id: self.id)
      end
    end
  end

字符串
然而,当我尝试在控制台中使用Author.all.find_each(&:connect_to_user)执行此操作时,它给了我一个“堆栈级别太深”错误,并使所有内容崩溃。
我看了一些涉及pluck的帖子,比如this one,但是我找不到任何有用的东西。
我还尝试了一个控制器方法,如下所示:

User.all.find_each do |user|
  authors = Author.where(email: user.email)
  authors.each do |author|
    author.update(user_id: user.id)
  end
end


但它仍然是“堆栈级别太深”。
谁能帮我重构的方式不会让我的电脑开始喘息和吸烟?

6pp0gazn

6pp0gazn1#

我将向User模型添加一个类似的方法,它将根据用户的电子邮件地址将所有匹配的authors连接到当前的User示例。

# in app/model/user.rb
def find_and_connect_authors_with_same_email
  authors = Author.where(email: email)
  authors.update_all(user_id: id)
end

字符串
并会这样调用它来将所有现有用户与作者连接起来:

User.find_each(&:find_and_connect_authors_with_same_email)


请记住,这只会根据用户和作者的电子邮件地址连接一次。但当电子邮件更改或创建新记录时,则不会再次出现。最好在save之前对AuthorUser记录运行回调。或者不通过电子邮件匹配,添加所有并仅存储User模型上的电子邮件,并确保没有没有关联UserAuthor。但是,什么是有意义的,什么是实际的,取决于您的应用程序和特定的用例。

相关问题