2012-08-15 72 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