1

我可能会做这个错误的整体,但也许有人可以唧唧喳喳帮助。构建has_many:通过新对象

问题

我希望能够建立在一个未保存的对象的关系,使得这会工作:

v = Video.new 
v.title = "New Video" 
v.actors.build(:name => "Jonny Depp") 
v.save! 

要添加到这一点,这将通过生成自定义的方法,我试图修改的工作,即做以下事情:

v = Video.new 
v.title = "Interesting cast..." 
v.actors_list = "Jonny Depp, Clint Eastwood, Rick Moranis" 
v.save 

此方法看起来像这样在vid eo.rb

def actors_list=value 
    #Clear for existing videos 
    self.actors.clear 

    value.split(',').each do |actorname| 
    if existing = Actor.find_by_name(actorname.strip) 
     self.actors << existing 
    else 
     self.actors.build(:name => actorname.strip) 
    end 
    end 
end 

我期待什么

v.actors.map(&:name) 
=> ["Jonny Depp", "Clint Eastwood", "Rick Moranis"] 

Unfortunatey,这些策略既没有创造一个演员,也没有关联。哦,是的,你可能会问我要的是:在

video.rb

has_many :actor_on_videos 
has_many :actors, :through => :actor_on_videos 

accepts_nested_attributes_for :actors 

我也尝试修改actors_list=方法,例如

def actors_list=value 
    #Clear for existing videos 
    self.actors.clear 

    value.split(',').each do |actorname| 
    if existing = Actor.find_by_name(actorname.strip) 
     self.actors << existing 
    else 
     self.actors << Actor.create!(:name => actorname.strip) 
    end 
    end 
end 

,它创造的演员,但如果视频在保存时失败,我宁愿不创建Actor。

所以我接近这个错误?还是我错过了一些明显的东西?

回答

1

试试这个:

class Video < ActiveRecord::Base 

    has_many :actor_on_videos 
    has_many :actors, :through => :actor_on_videos 

    attr_accessor :actors_list 
    after_save :save_actors 

    def actors_list=names 
    (names.presence || "").split(",").uniq.map(&:strip).tap do |new_list| 
     @actors_list = new_list if actors_list_changes?(new_list) 
    end 
    end 

    def actors_list_changes?(new_list) 
    new_record? or 
     (actors.count(:conditions => {:name => new_list}) != new_list.size) 
    end 

    # save the actors in after save. 
    def save_actors 
    return true if actors_list.blank? 
    # create the required names 
    self.actors = actors_list.map {|name| Actor.find_or_create_by_name(name)} 
    true 
    end 
end 
+0

非常感谢!奇妙的作品。提出一些编辑建议,以便我必须对其进行更改才能使其起作用 – 2012-03-18 21:15:52

+0

@KyleMacey,您必须执行的编辑有哪些? – 2012-03-18 22:22:46

+0

我以为你会和你的代表一起看到他们,对不起。我还没有在那里。在这里你去>> http://pastebin.com/2LaXGe4G – 2012-03-18 22:51:46

0

您不能将孩子分配给没有ID的对象。您需要将演员存储在新视频对象中,并在视频保存并保存ID后保存这些记录。