就像在rails中的動態查找程序方法一樣,有沒有辦法爲關聯模型提供動態查找程序方法?在rails應用程序中動態添加named_scopes
考慮以下車型
class User
attr_accessible :name, :phone_no
has_many :notes
end
class Note
belongs_to :user
attr_acccessible :note
end
我怎麼能叫音符屬性的動態取景器從用戶對象?
就像在rails中的動態查找程序方法一樣,有沒有辦法爲關聯模型提供動態查找程序方法?在rails應用程序中動態添加named_scopes
考慮以下車型
class User
attr_accessible :name, :phone_no
has_many :notes
end
class Note
belongs_to :user
attr_acccessible :note
end
我怎麼能叫音符屬性的動態取景器從用戶對象?
作用域是類方法,因此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
什麼是您的Rails/Ruby版本? – Andrei 2012-08-10 13:55:26
Ruby版本:1.8.7 Rails版本:3.0.4 beta – 2012-08-11 04:08:44