2010-06-30 184 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