与find_or_create accepts_nested_attributes_for? [英] accepts_nested_attributes_for with find_or_create?

查看:272
本文介绍了与find_or_create accepts_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?

通过示例的方式:

说我有三种模式,团队,成员和球员,每队通过成员的has_many玩家,玩家可以属于多个团队。然后组队模式可能会接受玩家嵌套属性,但是这意味着每个玩家通过整合后的团队+播放器(S)的形式提交将创建一个新的播放器的记录。

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.

我应该如何去做事,如果我只想创造一个新纪录的球员这种方式如果没有一个球员具有相同的名称?如果没有的<​​em>是的玩家使用相同的名称,应创建新的播放记录,而是正确的玩家应该发现,与新球队战绩有关。

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.

推荐答案

当你定义自动保存协会钩,正常的code路径被跳过,你的方法被调用来代替。因此,你可以这样做:

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

这code是未经测试,但它应该是pretty的多你所需要的。

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

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

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