Ruby On Rails 面接の質問と回答
Question: What is Scope in Ruby on Rails?Answer:Scopes are nothing more than SQL scope fragments. By using these fragments one can cut down on having to write long queries each time you access content. Say you typically access content as shown below: @posts = Post.where("published_at IS NOT NULL AND posts.published_at <= "+ Time.now)Ruby offers you a nice way to put the where condition inside a scope statement as shown below. class Post < ActiveRecord::Base
scope :published, lambda {
{ :conditions =>
["posts.published_at IS NOT NULL AND posts.published_at <= ?", Time.now]
}
}
scope :recent, :order => "posts.published_at DESC"
endNow you can simply access the published posts as: Post.published @posts = Post.published Also, you can access recent posts as @recent_posts = Post.recent |
復習用に保存
この項目をブックマークに追加したり、難しい内容としてマークしたり、復習セットに入れたりできます。
役に立ちましたか? はい いいえ
ユーザー評価で最も役立つ内容:
- What is Ruby On Rails?
- Why Ruby on Rails?
- Explain how (almost) everything is an object in Ruby.
- What are Gems and which are some of your favorites?
- How would you declare and use a constructor in Ruby?