2012-08-15 31 views
5

我有模型分类和产品。如果我使用category.products << new_product,则该项目将被添加到数组中,并且记录将保存到数据库中。我尝试将下面的“add”方法添加到数组类中,并且它将new_product添加到数组中,但它不会将其保存到数据库中。这是为什么?将添加方法添加到ActiveRecord阵列

class Array 
    def add(item) 
    self << item 
    end 
end 

更新:

collection_proxy.rb有以下方法:

def <<(*records) 
    proxy_association.concat(records) && self 
end 
alias_method :push, :<< 

所以下面的扩建工程:

class ActiveRecord::Relation 
    def add(*records) 
    proxy_association.concat(records) && self 
    end 
end 

解决方案:

添加的别名CollectionProxy:

class ActiveRecord::Associations::CollectionProxy 
    alias_method :add, :<< 
end 
+0

由于Rails协会是不是数组,他们只是声称他们是。 – 2012-08-15 21:37:09

+0

他们是什么?我怎样才能添加一个“添加”方法? – Manuel 2012-08-15 21:41:51

回答

2

编辑:曼纽尔找到了一个更好的解决方案

class ActiveRecord::Associations::CollectionProxy 
    alias_method :add, :<< 
end 

原液:

这应该让你开始。这并不完美。

class ActiveRecord::Relation 
    def add(attrs) 
    create attrs 
    end 
end 

而不是火了您的型号名称一个新的Rails项目,我只是用一个我有下面的例子:

1.9.3p194 :006 > Artist.create(:first_name => "Kyle", :last_name => "G", :email => "[email protected]") 
=> #<Artist id: 5, first_name: "Kyle", last_name: "G", nickname: nil, email: "[email protected]", created_at: "2012-08-16 04:08:30", updated_at: "2012-08-16 04:08:30", profile_image_id: nil, active: true, bio: nil> 
1.9.3p194 :007 > Artist.first.posts.count 
=> 0 
1.9.3p194 :008 > Artist.first.posts.add :title => "Foo", :body => "Bar" 
=> #<Post id: 12, title: "Foo", body: "Bar", artist_id: 5, created_at: "2012-08-16 04:08:48", updated_at: "2012-08-16 04:08:48"> 
1.9.3p194 :009 > Artist.first.posts.count 
=> 1 
+0

谢谢。你知道为什么它失败时,你不是作为一个散列添加新记录,而是传递一个对象? (我得到“NoMethodError:未定义的方法'stringify_keys'”) – Manuel 2012-08-16 04:31:55

+0

@Manuel yes,'add'正在调用'create',它期望属性作为散列。你可以改变方法,像'create item.attributes',但是你可能会遇到一些保护属性的问题。考虑从对象中挑选出你需要的。 – Kyle 2012-08-16 04:33:45

+0

不是:(创建item.attributes在数据库中创建记录,但不会创建关系(在您的情况下,artist_id为null) – Manuel 2012-08-16 05:11:21