11月26日 用seed,预加载种子文件; Case 条件语句。网址的参数如何传递,; Query--自定义scopes

在seed文件中输入一些预加载的种子job,注意属性和值都要有: 
❌错误,我输入contact_email的时候value值是空的,这样不能正确生成。

正确✅: 

for i in 1..10 do

  Job.create(title:"No#{i}",description:"这是关于No#{i}的介绍",wage_upper_bound: rand(50..99)*100,
              wage_lower_bound:rand(10..50)*50,is_hidden:"false",contact_email:"11e")
end

然后在terminal输入rake db:seed

 


 case语法:

 

  def index
    @jobs = case params[:order]
    when 'by_lower_bound'
      Job.where(:is_hidden => false ).order("wage_lower_bound DESC")
    when 'by_upper_bound'
      Job.where(:is_hidden => false ).order("wage_upper_bound desc")
    else
      Job.where(:is_hidden => false ).order("created_at desc")
    end
  end

Active Record Query Interface

路径传递参数的用法:网址里面带参数order(也是query)

job_path(里面可以传id参数来调用controller里面的show), 

jobs_path(里面也可以传设定的参数,如👇的,调用的是controller里面的index action)

<li><%= link_to("按照薪资下限排序", jobs_path(:order => "by_lower_bound") )%></li> 

参数传递给controller后执行相应的action内的查询结果,最后给view视图并生成 /jobs?order=by_lower_bound 这样的网址 

 


Query--14 Scopes

Scoping allows you to specify commonly-used queries which can be referenced as method calls on the association objects or models.

作用域 允许 你 定义 经常用到的 查询语句,可以作为method召唤关联的对象或模型。

query语句的大量method如where,joins,includes都可以和scopes一起使用。

Scope methods return 一个relation object 允许其他method调用它,因此scope可以被别的scope调用

class Article < ApplicationRecord
  scope :published, -> { where(published: true) }
end

 等同于

class Article < ApplicationRecord
  def self.published
    where(published: true)
  end
end
 

 可以使用复杂的嵌套scope.因为scope可以被别的scope调用。

class Article < ApplicationRecord
  scope :published,               -> { where(published: true) }
  scope :published_and_commented, -> { published.where("comments_count > 0") }
end

14.1 Passing in arguments

 Your scope can take arguments:

 pasting

14.2 Using conditionals

Your scope can utilize conditionals; 

14.4 Merging of scopes

比较复杂的混合查询。

14.5 Removing All Scoping

unscoped method,配合默认的scope

 原文:英语

http://guides.rubyonrails.org/active_record_querying.html#passing-in-arguments 

posted @ 2017-11-26 19:03  Mr-chen  阅读(234)  评论(0编辑  收藏  举报