通过 find_or_create 接受_nested_attributes_for? [英] accepts_nested_attributes_for with find_or_create?

查看:21
本文介绍了通过 find_or_create 接受_nested_attributes_for?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Rails 的 accepts_nested_attributes_for 方法取得了巨大的成功,但是如果记录已经存在,我如何创建新记录?

I'm using Rails' accepts_nested_attributes_for method with great success, but how can I have it not create new records if a record already exists?

举例:

假设我有三个模型,Team、Membership 和 Player,每支球队有_many 球员,球员可以属于许多球队.然后,团队模型可能会接受球员的嵌套属性,但这意味着通过组合团队 + 球员形式提交的每个球员都将被创建为新球员记录.

Say I've got three models, Team, Membership, and Player, and each team has_many players through memberships, and players can belong to many teams. The Team model might then accept nested attributes for players, but that means that each player submitted through the combined team+player(s) form will be created as a new player record.

如果我只想在没有同名玩家的情况下以这种方式创建新的玩家记录,我应该怎么做?如果存在同名球员,则不应创建新的球员记录,而是应找到正确的球员并将其与新的球队记录相关联.

How should I go about doing things if I want to only create a new player record this way if there isn't already a player with the same name? If there is a player with the same name, no new player records should be created, but instead the correct player should be found and associated with the new team record.

推荐答案

当您为自动保存关联定义挂钩时,将跳过正常的代码路径,而是调用您的方法.因此,您可以这样做:

When you define a hook for autosave associations, the normal code path is skipped and your method is called instead. Thus, you can do this:

class Post < ActiveRecord::Base
  belongs_to :author, :autosave => true
  accepts_nested_attributes_for :author

  # If you need to validate the associated record, you can add a method like this:
  #     validate_associated_record_for_author
  def autosave_associated_records_for_author
    # Find or create the author by name
    if new_author = Author.find_by_name(author.name)
      self.author = new_author
    else
      self.author.save!
    end
  end
end

此代码未经测试,但应该是您所需要的.

This code is untested, but it should be pretty much what you need.

这篇关于通过 find_or_create 接受_nested_attributes_for?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆