2012-08-10 26 views
0

就像在rails中的動態查找程序方法一樣,有沒有辦法爲關聯模型提供動態查找程序方法?在rails應用程序中動態添加named_scopes

考慮以下車型

class User 
    attr_accessible :name, :phone_no 
    has_many :notes 
end 

class Note 
    belongs_to :user 
    attr_acccessible :note 
end 

我怎麼能叫音符屬性的動態取景器從用戶對象?

+0

什麼是您的Rails/Ruby版本? – Andrei 2012-08-10 13:55:26

+0

Ruby版本:1.8.7 Rails版本:3.0.4 beta – 2012-08-11 04:08:44

回答

1

作用域是類方法,因此User.scope_name(更多範圍在這裏:http://guides.rubyonrails.org/active_record_querying.html#scopes)。如果你想找到屬於該用戶對象特定的音符,你可以定義一個實例方法 - 是這樣的:

def note_with_content(content_string) 
    self.notes.where(:content => "#{content_string}") 
end 

def last_note 
    self.notes.last 
end 

而且使用方式如下:

@user.note_with_content("This is a note") 

@user.last_note 
+0

嗯你的答案是好的,但如果我必須動態添加這些實例方法呢?假設一個新的屬性動態添加到Note類中,那麼我想爲該屬性提供一個實例方法。我怎樣才能動態地做到這一點? – 2012-08-11 04:12:40

+0

'def note_with_attribute(attribute_name,value)'''self.notes.where(「#{attribute_name}」=>「#{value}」)'//'end' – Andrei 2012-08-11 15:49:54

+0

^^^您可以隨時傳入通過 – Andrei 2012-08-11 15:52:10

相關問題