2010-06-30 98 views
0

如何更改find​​方法的activerecord模型默認行爲? 例如,我要搜索的Drupal節點數據庫中的所有書籍,但Drupal使用只有一個表的所有數據,並使用「類型」欄找出型爲Drupal數據庫創建AR模型

class Book < ActiveRecord::Base 
    set_table_name 'node' 

    def find(*args) 
    :conditions => {:type => 'book'} 
    super 
    end 
end 

這是正確的做法解決這個問題?

+0

是否使用CCK(內容contstruction套件,也被稱爲content.module)?在這種情況下,你的表格甚至會更加動態。 – berkes 2010-07-01 17:34:20

+0

是的,這個節點類型中有cck字段。但是,例如,我只是試圖獲得書籍節點。 我打算寫一個rails插件,就像acts_as_drupal_node – vrsmn 2010-07-05 17:45:13

回答

1

我已經解決了這個創造了節點模型,並使用named_scopes

結果是這個

class Node 
    set_table_name 'node' 
    set_primary_key 'nid' 
    named_scope :book, :conditions => {:type => 'book'} 

    # if i don't overwrite this method, i would get an error when i try to use the type column 
    def self.inheritance_column 
    "rails_type" 
    end 
end 

它的工作原理,但並不像做的東西的軌道的方式。如果我很快得到足夠多的時間,我會嘗試寫一庫訪問使用類似acts_as_drupal_node Drupal的數據

現在我可以用獲取所有簿條目:

@books = Node.book.all 
+0

在你的情況下,我將使用**書籍**作爲範圍的名稱,而在Rails 3中,你可以使用'scope'而不是'named_scope' – 2011-07-26 17:18:13