2020年2月18日 星期二

Model中的scope方法,排序,判斷式

https://railsbook.tw/chapters/16-model-basic.html#scope-and-class-method

自己創造scope方法

重點在於將邏輯從controller抽出到model裡面

修改 app/models/post.rb,加入一行 scope :recent, -> { order("created_at DESC")}

app/models/post.rb
class Post < ApplicationRecord
    # ... 略
  scope :recent, -> { order("created_at DESC")}#排序
  scope :available, -> { where(is_available: true) }#is_available
  scope :price_over, ->(p) { where(["price > ?", p]) }#價格是否大於
end

app/controllers/groups_controller.rb
  def show
    @group = Group.find(params[:id])
    @posts = @group.posts.recent >>這樣漂亮乾淨多了
  end

公用的方法

.created_at >何時創建的
.updated_at >何時更新的

沒有留言:

張貼留言

cloud9上面開發rails

 使用IAM身分登入,以免有資安問題。(用admin帳號登入,創建iam使用者,然後在上面的連結登入) 選擇 ubuntu18.04 減少查詢成本。 已經是超級使用者了,sudo 什麼都不需要輸入密碼了。 $ ruby -v  檢查 ruby使用的版本>>2.6.3,...